From c4d75234b088e631c2ab5f445cf07ec1880c082a Mon Sep 17 00:00:00 2001 From: Rushdi Date: Thu, 24 Feb 2022 23:45:13 +0530 Subject: [PATCH 01/41] Initiate traccar to locate the geo locations in the map --- .../org.wso2.carbon.device.mgt.core/pom.xml | 15 ++ .../impl/DeviceInformationManagerImpl.java | 19 ++ .../DeviceManagementProviderService.java | 4 +- .../DeviceManagementProviderServiceImpl.java | 18 +- .../api/service/DeviceAPIClientService.java | 33 +++ .../api/service/addons/TrackerClient.java | 139 ++++++++++++ .../impl/DeviceAPIClientServiceImpl.java | 44 ++++ .../core/traccar/common/TraccarClient.java | 33 +++ .../common/TraccarHandlerConstants.java | 29 +++ .../common/beans/TraccarDeviceInfo.java | 206 ++++++++++++++++++ .../core/traccar/common/config/Property.java | 49 +++++ .../common/config/TraccarConfiguration.java | 68 ++++++ .../traccar/common/config/TraccarGateway.java | 87 ++++++++ .../config/TraccarConfigurationManager.java | 102 +++++++++ 14 files changed, 841 insertions(+), 5 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TrackerClient.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarClient.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarHandlerConstants.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarDeviceInfo.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/Property.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/TraccarConfiguration.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/TraccarGateway.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/core/config/TraccarConfigurationManager.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml index 7ec5e847b63..d5618ef1d84 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml @@ -342,6 +342,21 @@ com.google.guava guava + + com.fasterxml.jackson.core + jackson-databind + 2.11.2 + + + io.github.openfeign + feign-okhttp + + + org.wso2.orbit.com.squareup.okhttp + okhttp + 4.2.0.wso2v1 + compile + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java index 47f13ae9681..14a01479def 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java @@ -18,6 +18,7 @@ package org.wso2.carbon.device.mgt.core.device.details.mgt.impl; +import com.google.gson.Gson; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -43,10 +44,13 @@ import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsMgtDA import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.report.mgt.Constants; 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.beans.TraccarDeviceInfo; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil; import org.wso2.carbon.user.api.UserStoreException; +import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Calendar; @@ -385,6 +389,18 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { // LOCATION_EVENT_STREAM_DEFINITION, "1.0.0", metaData, new Object[0], payload // ); } + + //Traccar update lat lon + TraccarDeviceInfo trackerinfo = new TraccarDeviceInfo(device.getDeviceIdentifier(), + deviceLocation.getUpdatedTime().getTime(), + deviceLocation.getLatitude(), deviceLocation.getLongitude(), + deviceLocation.getBearing(), deviceLocation.getSpeed()); + + DeviceAPIClientServiceImpl dac= new DeviceAPIClientServiceImpl(); + String deviceAPIClientResponse=dac.updateLocation(trackerinfo); + log.info("Location Update "+ new Gson().toJson(deviceAPIClientResponse)); + //Traccar update lat lon + DeviceManagementDAOFactory.commitTransaction(); } catch (TransactionManagementException e) { throw new DeviceDetailsMgtException("Transactional error occurred while adding the device location " + @@ -398,6 +414,9 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { // } catch (DataPublisherConfigurationException e) { // DeviceManagementDAOFactory.rollbackTransaction(); // throw new DeviceDetailsMgtException("Error occurred while publishing the device location information.", e); + } catch (IOException e) { + log.error("Error on Traccar" + e); + //e.printStackTrace(); } finally { DeviceManagementDAOFactory.closeConnection(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java index 4b1a424d27a..4e283160594 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java @@ -66,8 +66,8 @@ 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.DeviceTypeVersion; import org.wso2.carbon.device.mgt.common.geo.service.GeoCluster; -import org.wso2.carbon.device.mgt.common.geo.service.GeoCoordinate; +import java.io.IOException; import java.sql.SQLException; import java.sql.Timestamp; import java.util.Collection; @@ -677,7 +677,7 @@ public interface DeviceManagementProviderService { boolean modifyEnrollment(Device device) throws DeviceManagementException; - boolean enrollDevice(Device device) throws DeviceManagementException; + boolean enrollDevice(Device device) throws DeviceManagementException, IOException; boolean saveConfiguration(PlatformConfiguration configuration) throws DeviceManagementException; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index d9bb601faeb..3e430021d4a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -112,13 +112,14 @@ 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.DeviceTypeVersion; 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.DeviceManagementServiceComponent; import org.wso2.carbon.device.mgt.core.internal.PluginInitializationListener; import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataDAO; import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOFactory; import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; +import org.wso2.carbon.device.mgt.core.traccar.api.service.impl.DeviceAPIClientServiceImpl; +import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDeviceInfo; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.email.sender.core.ContentProviderInfo; import org.wso2.carbon.email.sender.core.EmailContext; @@ -145,7 +146,6 @@ import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; -//import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; public class DeviceManagementProviderServiceImpl implements DeviceManagementProviderService, PluginInitializationListener { @@ -213,7 +213,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } @Override - public boolean enrollDevice(Device device) throws DeviceManagementException { + public boolean enrollDevice(Device device) throws DeviceManagementException, IOException { if (device == null) { String msg = "Received empty device for device enrollment"; log.error(msg); @@ -394,6 +394,18 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv status = true; } + //Traccar update Latitude Longitude + String lastUpdatedTime = String.valueOf((new Date().getTime())); + TraccarDeviceInfo traccarDeviceInfo = new TraccarDeviceInfo(device.getName(), device.getDeviceIdentifier(), + "online", "false", lastUpdatedTime, "", "", "", "", + "", ""); + DeviceAPIClientServiceImpl dac= new DeviceAPIClientServiceImpl(); + String deviceAPIClientResponse=dac.addDevice(traccarDeviceInfo); + if (log.isDebugEnabled()) { + log.debug("Location Update "+ new Gson().toJson(deviceAPIClientResponse)); + } + //Traccar update Latitude Longitude + if (status) { addDeviceToGroups(deviceIdentifier, device.getEnrolmentInfo().getOwnership()); if (enrollmentConfiguration != null) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java new file mode 100644 index 00000000000..14bdcc9d244 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java @@ -0,0 +1,33 @@ +/* + * 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.core.traccar.common.beans.TraccarDeviceInfo; + +import java.io.IOException; + +public interface DeviceAPIClientService { + + String updateLocation(TraccarDeviceInfo deviceInfo) throws IOException; + + String addDevice(TraccarDeviceInfo deviceInfo) throws IOException; + + String deleteDevice(TraccarDeviceInfo deviceInfo) throws IOException; +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TrackerClient.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TrackerClient.java new file mode 100644 index 00000000000..d2cce2ddd2d --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TrackerClient.java @@ -0,0 +1,139 @@ +/* + * 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 okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.json.JSONObject; +import org.wso2.carbon.device.mgt.core.traccar.common.TraccarClient; +import org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants; +import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDeviceInfo; +import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarGateway; +import org.wso2.carbon.device.mgt.core.traccar.core.config.TraccarConfigurationManager; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import static org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants.ENDPOINT; +import static org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants.AUTHORIZATION; +import static org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants.AUTHORIZATION_KEY; +import static org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants.MAIN_ENDPOINT; + +public class TrackerClient implements TraccarClient { + private static final Log log = LogFactory.getLog(TrackerClient.class); + + public String updateLocation(TraccarDeviceInfo deviceInfo) throws IOException{ + //Retrieve the traccar Gateway by passing the Gateway name + TraccarGateway traccarGateway = getTraccarGateway(); + + //Retrieve the properties in the Traccar Gateway by passing the property name + String endpoint = traccarGateway.getPropertyByName(ENDPOINT).getValue(); + + OkHttpClient client = new OkHttpClient().newBuilder().build(); + Request request = new Request.Builder() + .url(endpoint+"id="+deviceInfo.getDeviceIdentifier()+ + "×tamp="+deviceInfo.getTimestamp()+ + "&lat="+deviceInfo.getLat()+"&lon="+deviceInfo.getLon()+ + "&bearing="+deviceInfo.getBearing()+"&speed="+deviceInfo.getSpeed()+"&ignition=true") + .method("GET", null) + .build(); + Response response = client.newCall(request).execute(); + log.info(String.valueOf(response)); + return String.valueOf(response); + } + + public String addDevice(TraccarDeviceInfo deviceInfo) throws IOException{ + + //Retrieve the traccar Gateway by passing the Gateway name + TraccarGateway traccarGateway = getTraccarGateway(); + + //Retrieve the properties in the Traccar Gateway by passing the property name + String endpoint = traccarGateway.getPropertyByName(MAIN_ENDPOINT).getValue(); + String authorization = traccarGateway.getPropertyByName(AUTHORIZATION).getValue(); + String authorizationKey = traccarGateway.getPropertyByName(AUTHORIZATION_KEY).getValue(); + + OkHttpClient client = new OkHttpClient().newBuilder().build(); + MediaType mediaType = MediaType.parse("application/json"); + + JSONObject data = new JSONObject(); + data.put("name", deviceInfo.getDeviceName()); + data.put("uniqueId", deviceInfo.getUniqueId()); + data.put("status", deviceInfo.getStatus()); + data.put("disabled", deviceInfo.getDisabled()); + data.put("lastUpdate", deviceInfo.getLastUpdate()); + data.put("positionId", deviceInfo.getPositionId()); + data.put("groupId", deviceInfo.getGroupId()); + data.put("phone", deviceInfo.getPhone()); + data.put("model", deviceInfo.getModel()); + data.put("contact", deviceInfo.getContact()); + data.put("category", deviceInfo.getCategory()); + List geofenceIds = new ArrayList<>(); + data.put("geofenceIds", geofenceIds); + data.put("attributes", new JSONObject()); + + RequestBody body = RequestBody.create(mediaType, data.toString()); + + Request request = new Request.Builder() + .url(endpoint+"/devices") + .method("POST", body) + .addHeader("Content-Type", "application/json") + .addHeader(authorization, authorizationKey) + .build(); + Response response = client.newCall(request).execute(); + + return String.valueOf(response); + } + + // /TODO FIX THIS WITH GET REQUEST + public String deleteDevice(TraccarDeviceInfo deviceInfo){ + + //Retrieve the traccar Gateway by passing the Gateway name + TraccarGateway traccarGateway = getTraccarGateway(); + + //Retrieve the properties in the Traccar Gateway by passing the property name + String endpoint = traccarGateway.getPropertyByName(MAIN_ENDPOINT).getValue(); + String authorization = traccarGateway.getPropertyByName(AUTHORIZATION).getValue(); + String authorizationKey = traccarGateway.getPropertyByName(AUTHORIZATION_KEY).getValue(); + + /* + OkHttpClient client = new OkHttpClient().newBuilder().build(); + MediaType mediaType = MediaType.parse("text/plain"); + RequestBody body = RequestBody.create(mediaType, ""); + Request request = new Request.Builder() + .url("endpoint+"/devices/"+deviceInfo) + .method("DELETE", body) + .addHeader(authorization, authorizationKey) + .build(); + Response response = client.newCall(request).execute(); + */ + + return ""; + } + + private TraccarGateway getTraccarGateway(){ + return TraccarConfigurationManager.getInstance().getTraccarConfig().getTraccarGateway(TraccarHandlerConstants.GATEWAY_NAME); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java new file mode 100644 index 00000000000..8fbe31caff4 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java @@ -0,0 +1,44 @@ +/* + * 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.wso2.carbon.device.mgt.core.traccar.api.service.DeviceAPIClientService; +import org.wso2.carbon.device.mgt.core.traccar.api.service.addons.TrackerClient; +import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDeviceInfo; + +import java.io.IOException; + +public class DeviceAPIClientServiceImpl implements DeviceAPIClientService { + + public String updateLocation(TraccarDeviceInfo deviceInfo) throws IOException { + TrackerClient client = new TrackerClient(); + return (client.updateLocation(deviceInfo)); + } + + public String addDevice(TraccarDeviceInfo deviceInfo) throws IOException { + TrackerClient client = new TrackerClient(); + return (client.addDevice(deviceInfo)); + } + + public String deleteDevice(TraccarDeviceInfo deviceInfo) throws IOException { + TrackerClient client = new TrackerClient(); + return (client.deleteDevice(deviceInfo)); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarClient.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarClient.java new file mode 100644 index 00000000000..7cd977c58f2 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarClient.java @@ -0,0 +1,33 @@ +/* + * 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; + +import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDeviceInfo; + +import java.io.IOException; + +public interface TraccarClient { + + String updateLocation(TraccarDeviceInfo deviceInfo) throws IOException; + + String addDevice(TraccarDeviceInfo deviceInfo) throws IOException; + + String deleteDevice(TraccarDeviceInfo deviceInfo) throws IOException; +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarHandlerConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarHandlerConstants.java new file mode 100644 index 00000000000..f1c4d6c5157 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarHandlerConstants.java @@ -0,0 +1,29 @@ +/* + * 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 final String TRACCAR_CONFIG_XML_NAME = "traccar-config.xml"; + public static final String GATEWAY_NAME = "sample"; + public static final String MAIN_ENDPOINT = "api-endpoint"; + public static final String ENDPOINT = "add-location-api-endpoint"; + public static final String AUTHORIZATION = "authorization"; + public static final String AUTHORIZATION_KEY = "authorization-key"; +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarDeviceInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarDeviceInfo.java new file mode 100644 index 00000000000..f0e389c24a5 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarDeviceInfo.java @@ -0,0 +1,206 @@ +/* + * 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 TraccarDeviceInfo { + private String deviceIdentifier; + private Long timestamp; + private Double lat; + private Double lon; + private Float bearing; + private Float speed; + + 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 TraccarDeviceInfo(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 TraccarDeviceInfo(String deviceName, String uniqueId, String status, String disabled, String lastUpdate, + String positionId, String groupId, String phone, String model, String contact, + String category){ + 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 TraccarDeviceInfo(){ } + + 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; + } + + 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 getDeviceIdentifier() { + return deviceIdentifier; + } + + public void setDeviceIdentifier(String deviceIdentifier) { + this.deviceIdentifier = deviceIdentifier; + } + + 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; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/Property.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/Property.java new file mode 100644 index 00000000000..8aca8595ae3 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/Property.java @@ -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; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/TraccarConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/TraccarConfiguration.java new file mode 100644 index 00000000000..ee355d31f02 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/TraccarConfiguration.java @@ -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 traccarGateways; + + @XmlElementWrapper(name = "Gateways") + @XmlElement(name = "Gateway") + public List getTraccarGateways() { + return traccarGateways; + } + + public void setTraccarGateways(List 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; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/TraccarGateway.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/TraccarGateway.java new file mode 100644 index 00000000000..87f2a7fa025 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/TraccarGateway.java @@ -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 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 getProperties() { + return properties; + } + + public void setProperties(List 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; + } +} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/core/config/TraccarConfigurationManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/core/config/TraccarConfigurationManager.java new file mode 100644 index 00000000000..d1164bdb352 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/core/config/TraccarConfigurationManager.java @@ -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.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; + } +} From 8d99123ec1e30941e4ceea3605ec5f7de534e284 Mon Sep 17 00:00:00 2001 From: Rushdi Date: Sat, 26 Feb 2022 02:39:47 +0530 Subject: [PATCH 02/41] Update with Traccar Dis-Enrolling a Device via UEM --- .../impl/DeviceInformationManagerImpl.java | 4 +- .../DeviceManagementProviderServiceImpl.java | 14 +- .../api/service/DeviceAPIClientService.java | 9 +- .../api/service/addons/TrackerClient.java | 73 +++++-- .../impl/DeviceAPIClientServiceImpl.java | 11 +- .../core/traccar/common/TraccarClient.java | 12 +- .../traccar/common/beans/TraccarDevice.java | 106 +++++++++ .../common/beans/TraccarDeviceInfo.java | 206 ------------------ .../traccar/common/beans/TraccarPosition.java | 90 ++++++++ 9 files changed, 281 insertions(+), 244 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarDevice.java delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarDeviceInfo.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarPosition.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java index 14a01479def..1650c00713a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java @@ -45,7 +45,7 @@ import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.report.mgt.Constants; 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.beans.TraccarDeviceInfo; +import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarPosition; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil; import org.wso2.carbon.user.api.UserStoreException; @@ -391,7 +391,7 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { } //Traccar update lat lon - TraccarDeviceInfo trackerinfo = new TraccarDeviceInfo(device.getDeviceIdentifier(), + TraccarPosition trackerinfo = new TraccarPosition(device.getDeviceIdentifier(), deviceLocation.getUpdatedTime().getTime(), deviceLocation.getLatitude(), deviceLocation.getLongitude(), deviceLocation.getBearing(), deviceLocation.getSpeed()); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 3e430021d4a..644444f1e76 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -119,7 +119,8 @@ 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.operation.mgt.CommandOperation; import org.wso2.carbon.device.mgt.core.traccar.api.service.impl.DeviceAPIClientServiceImpl; -import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDeviceInfo; +import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDevice; +import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarPosition; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.email.sender.core.ContentProviderInfo; import org.wso2.carbon.email.sender.core.EmailContext; @@ -396,7 +397,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv //Traccar update Latitude Longitude String lastUpdatedTime = String.valueOf((new Date().getTime())); - TraccarDeviceInfo traccarDeviceInfo = new TraccarDeviceInfo(device.getName(), device.getDeviceIdentifier(), + TraccarDevice traccarDeviceInfo = new TraccarDevice(device.getName(), device.getDeviceIdentifier(), "online", "false", lastUpdatedTime, "", "", "", "", "", ""); DeviceAPIClientServiceImpl dac= new DeviceAPIClientServiceImpl(); @@ -566,6 +567,15 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv deviceDAO.updateDevice(device, tenantId); DeviceManagementDAOFactory.commitTransaction(); this.removeDeviceFromCache(deviceId); + + //Traccar update Latitude Longitude + TraccarDevice traccarDeviceInfo = new TraccarDevice(device.getDeviceIdentifier()); + DeviceAPIClientServiceImpl dac= new DeviceAPIClientServiceImpl(); + String deviceAPIClientResponse=dac.disDevice(traccarDeviceInfo); + if (log.isDebugEnabled()) { + log.debug("Disenroll Device "+ new Gson().toJson(deviceAPIClientResponse)); + } + //Traccar update Latitude Longitude } catch (DeviceManagementDAOException e) { DeviceManagementDAOFactory.rollbackTransaction(); String msg = "Error occurred while dis-enrolling '" + deviceId.getType() + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java index 14bdcc9d244..a96fff1f863 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java @@ -19,15 +19,16 @@ package org.wso2.carbon.device.mgt.core.traccar.api.service; -import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDeviceInfo; +import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDevice; +import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarPosition; import java.io.IOException; public interface DeviceAPIClientService { - String updateLocation(TraccarDeviceInfo deviceInfo) throws IOException; + String updateLocation(TraccarPosition deviceInfo) throws IOException; - String addDevice(TraccarDeviceInfo deviceInfo) throws IOException; + String addDevice(TraccarDevice deviceInfo) throws IOException; - String deleteDevice(TraccarDeviceInfo deviceInfo) throws IOException; + String disDevice(TraccarDevice deviceInfo) throws IOException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TrackerClient.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TrackerClient.java index d2cce2ddd2d..0cb7fc97c20 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TrackerClient.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TrackerClient.java @@ -19,6 +19,7 @@ package org.wso2.carbon.device.mgt.core.traccar.api.service.addons; +import com.google.gson.Gson; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; @@ -26,10 +27,13 @@ import okhttp3.RequestBody; import okhttp3.Response; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.json.JSONArray; +import org.json.JSONException; import org.json.JSONObject; import org.wso2.carbon.device.mgt.core.traccar.common.TraccarClient; import org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants; -import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDeviceInfo; +import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDevice; +import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarPosition; import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarGateway; import org.wso2.carbon.device.mgt.core.traccar.core.config.TraccarConfigurationManager; @@ -45,7 +49,26 @@ import static org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConst public class TrackerClient implements TraccarClient { private static final Log log = LogFactory.getLog(TrackerClient.class); - public String updateLocation(TraccarDeviceInfo deviceInfo) throws IOException{ + public Request getDeviceByDeviceIdentifier(String deviceId) { + //device identifier matches with traccar uniqueId + //Retrieve the traccar Gateway by passing the Gateway name + TraccarGateway traccarGateway = getTraccarGateway(); + + //Retrieve the properties in the Traccar Gateway by passing the property name + String endpoint = traccarGateway.getPropertyByName(MAIN_ENDPOINT).getValue(); + String authorization = traccarGateway.getPropertyByName(AUTHORIZATION).getValue(); + String authorizationKey = traccarGateway.getPropertyByName(AUTHORIZATION_KEY).getValue(); + + OkHttpClient client = new OkHttpClient().newBuilder().build(); + Request request = new Request.Builder() + .url(endpoint+"/devices?uniqueId="+deviceId) + .method("GET", null) + .addHeader(authorization, authorizationKey) + .build(); + return request; + } + + public String updateLocation(TraccarPosition deviceInfo) throws IOException { //Retrieve the traccar Gateway by passing the Gateway name TraccarGateway traccarGateway = getTraccarGateway(); @@ -65,8 +88,7 @@ public class TrackerClient implements TraccarClient { return String.valueOf(response); } - public String addDevice(TraccarDeviceInfo deviceInfo) throws IOException{ - + public String addDevice(TraccarDevice deviceInfo) throws IOException{ //Retrieve the traccar Gateway by passing the Gateway name TraccarGateway traccarGateway = getTraccarGateway(); @@ -95,7 +117,6 @@ public class TrackerClient implements TraccarClient { data.put("attributes", new JSONObject()); RequestBody body = RequestBody.create(mediaType, data.toString()); - Request request = new Request.Builder() .url(endpoint+"/devices") .method("POST", body) @@ -107,8 +128,7 @@ public class TrackerClient implements TraccarClient { return String.valueOf(response); } - // /TODO FIX THIS WITH GET REQUEST - public String deleteDevice(TraccarDeviceInfo deviceInfo){ + public String disDevice(TraccarDevice deviceInfo) throws IOException { //Retrieve the traccar Gateway by passing the Gateway name TraccarGateway traccarGateway = getTraccarGateway(); @@ -118,22 +138,33 @@ public class TrackerClient implements TraccarClient { String authorization = traccarGateway.getPropertyByName(AUTHORIZATION).getValue(); String authorizationKey = traccarGateway.getPropertyByName(AUTHORIZATION_KEY).getValue(); - /* - OkHttpClient client = new OkHttpClient().newBuilder().build(); - MediaType mediaType = MediaType.parse("text/plain"); - RequestBody body = RequestBody.create(mediaType, ""); - Request request = new Request.Builder() - .url("endpoint+"/devices/"+deviceInfo) - .method("DELETE", body) - .addHeader(authorization, authorizationKey) - .build(); - Response response = client.newCall(request).execute(); - */ - - return ""; + OkHttpClient client = new OkHttpClient(); + Request deviceDetails = getDeviceByDeviceIdentifier(deviceInfo.getDeviceIdentifier()); + Response response = client.newCall(deviceDetails).execute(); + + String result = response.body().string(); + String jsonData ="{"+ "\"geodata\": "+ result+ "}"; + + try { + JSONObject obj = new JSONObject(jsonData); + JSONArray geodata = obj.getJSONArray("geodata"); + JSONObject jsonResponse = geodata.getJSONObject(0); + + OkHttpClient client1 = new OkHttpClient(); + Request request1 = new Request.Builder() + .url(endpoint+"/devices/"+jsonResponse.getInt("id")).delete() + .addHeader(authorization, authorizationKey).build(); + Response response1 = client1.newCall(request1).execute(); + log.info(String.valueOf(response1)); + return String.valueOf(response1); + } catch (JSONException e) { + log.info("Delete Error "+e); + return String.valueOf(e); + } } private TraccarGateway getTraccarGateway(){ - return TraccarConfigurationManager.getInstance().getTraccarConfig().getTraccarGateway(TraccarHandlerConstants.GATEWAY_NAME); + return TraccarConfigurationManager.getInstance().getTraccarConfig().getTraccarGateway( + TraccarHandlerConstants.GATEWAY_NAME); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java index 8fbe31caff4..5fb27e3be45 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java @@ -21,24 +21,25 @@ package org.wso2.carbon.device.mgt.core.traccar.api.service.impl; import org.wso2.carbon.device.mgt.core.traccar.api.service.DeviceAPIClientService; import org.wso2.carbon.device.mgt.core.traccar.api.service.addons.TrackerClient; -import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDeviceInfo; +import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDevice; +import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarPosition; import java.io.IOException; public class DeviceAPIClientServiceImpl implements DeviceAPIClientService { - public String updateLocation(TraccarDeviceInfo deviceInfo) throws IOException { + public String updateLocation(TraccarPosition deviceInfo) throws IOException { TrackerClient client = new TrackerClient(); return (client.updateLocation(deviceInfo)); } - public String addDevice(TraccarDeviceInfo deviceInfo) throws IOException { + public String addDevice(TraccarDevice deviceInfo) throws IOException { TrackerClient client = new TrackerClient(); return (client.addDevice(deviceInfo)); } - public String deleteDevice(TraccarDeviceInfo deviceInfo) throws IOException { + public String disDevice(TraccarDevice deviceInfo) throws IOException { TrackerClient client = new TrackerClient(); - return (client.deleteDevice(deviceInfo)); + return (client.disDevice(deviceInfo)); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarClient.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarClient.java index 7cd977c58f2..bf2092af76a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarClient.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarClient.java @@ -19,15 +19,19 @@ package org.wso2.carbon.device.mgt.core.traccar.common; -import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDeviceInfo; +import okhttp3.Request; +import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDevice; +import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarPosition; import java.io.IOException; public interface TraccarClient { - String updateLocation(TraccarDeviceInfo deviceInfo) throws IOException; + String updateLocation(TraccarPosition deviceInfo) throws IOException; - String addDevice(TraccarDeviceInfo deviceInfo) throws IOException; + String addDevice(TraccarDevice deviceInfo) throws IOException; - String deleteDevice(TraccarDeviceInfo deviceInfo) throws IOException; + Request getDeviceByDeviceIdentifier(String deviceInfo) throws IOException; + + String disDevice(TraccarDevice deviceInfo) throws IOException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarDevice.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarDevice.java new file mode 100644 index 00000000000..29b4bc50098 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarDevice.java @@ -0,0 +1,106 @@ +/* + * 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 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(String deviceName, String uniqueId, String status, String disabled, String lastUpdate, + String positionId, String groupId, String phone, String model, String contact, + String category){ + 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 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;} + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarDeviceInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarDeviceInfo.java deleted file mode 100644 index f0e389c24a5..00000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarDeviceInfo.java +++ /dev/null @@ -1,206 +0,0 @@ -/* - * 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 TraccarDeviceInfo { - private String deviceIdentifier; - private Long timestamp; - private Double lat; - private Double lon; - private Float bearing; - private Float speed; - - 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 TraccarDeviceInfo(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 TraccarDeviceInfo(String deviceName, String uniqueId, String status, String disabled, String lastUpdate, - String positionId, String groupId, String phone, String model, String contact, - String category){ - 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 TraccarDeviceInfo(){ } - - 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; - } - - 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 getDeviceIdentifier() { - return deviceIdentifier; - } - - public void setDeviceIdentifier(String deviceIdentifier) { - this.deviceIdentifier = deviceIdentifier; - } - - 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; - } -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarPosition.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarPosition.java new file mode 100644 index 00000000000..d7bd927dbb4 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarPosition.java @@ -0,0 +1,90 @@ +/* + * 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 String deviceIdentifier; + private Long timestamp; + private Double lat; + private Double lon; + private Float bearing; + private Float 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 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; + } + +} From 4e3567202d9d14a084d114b8d113055db768482b Mon Sep 17 00:00:00 2001 From: Rushdi Date: Thu, 3 Mar 2022 21:55:27 +0530 Subject: [PATCH 03/41] Update with okhttclient pool and threading --- .../impl/DeviceInformationManagerImpl.java | 12 +- .../DeviceManagementProviderServiceImpl.java | 28 +- .../api/service/DeviceAPIClientService.java | 29 +- .../api/service/addons/TrackerClient.java | 256 +++++++++++------- .../impl/DeviceAPIClientServiceImpl.java | 26 +- .../core/traccar/common/TraccarClient.java | 12 +- .../common/TraccarHandlerConstants.java | 3 +- .../config/TraccarConfigurationException.java | 37 +++ 8 files changed, 269 insertions(+), 134 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/TraccarConfigurationException.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java index 1650c00713a..19a6c64ef2c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java @@ -45,7 +45,9 @@ import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.report.mgt.Constants; 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.beans.TraccarDevice; import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarPosition; +import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarConfigurationException; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil; import org.wso2.carbon.user.api.UserStoreException; @@ -390,16 +392,14 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { // ); } - //Traccar update lat lon + //Traccar update GPS Location TraccarPosition trackerinfo = new TraccarPosition(device.getDeviceIdentifier(), deviceLocation.getUpdatedTime().getTime(), deviceLocation.getLatitude(), deviceLocation.getLongitude(), deviceLocation.getBearing(), deviceLocation.getSpeed()); - DeviceAPIClientServiceImpl dac= new DeviceAPIClientServiceImpl(); - String deviceAPIClientResponse=dac.updateLocation(trackerinfo); - log.info("Location Update "+ new Gson().toJson(deviceAPIClientResponse)); - //Traccar update lat lon + dac.updateLocation(trackerinfo); + //Traccar update GPS Location DeviceManagementDAOFactory.commitTransaction(); } catch (TransactionManagementException e) { @@ -414,7 +414,7 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { // } catch (DataPublisherConfigurationException e) { // DeviceManagementDAOFactory.rollbackTransaction(); // throw new DeviceDetailsMgtException("Error occurred while publishing the device location information.", e); - } catch (IOException e) { + } catch (TraccarConfigurationException e) { log.error("Error on Traccar" + e); //e.printStackTrace(); } finally { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 644444f1e76..20fa0406a44 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -121,6 +121,7 @@ import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; import org.wso2.carbon.device.mgt.core.traccar.api.service.impl.DeviceAPIClientServiceImpl; import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDevice; import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarPosition; +import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarConfigurationException; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.email.sender.core.ContentProviderInfo; import org.wso2.carbon.email.sender.core.EmailContext; @@ -214,7 +215,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } @Override - public boolean enrollDevice(Device device) throws DeviceManagementException, IOException { + public boolean enrollDevice(Device device) throws DeviceManagementException { if (device == null) { String msg = "Received empty device for device enrollment"; log.error(msg); @@ -395,17 +396,19 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv status = true; } - //Traccar update Latitude Longitude + //enroll Traccar device String lastUpdatedTime = String.valueOf((new Date().getTime())); TraccarDevice traccarDeviceInfo = new TraccarDevice(device.getName(), device.getDeviceIdentifier(), "online", "false", lastUpdatedTime, "", "", "", "", "", ""); DeviceAPIClientServiceImpl dac= new DeviceAPIClientServiceImpl(); - String deviceAPIClientResponse=dac.addDevice(traccarDeviceInfo); - if (log.isDebugEnabled()) { - log.debug("Location Update "+ new Gson().toJson(deviceAPIClientResponse)); + try { + dac.addDevice(traccarDeviceInfo); + } catch (TraccarConfigurationException e) { + log.error("Error on Traccar add device" + e); + //e.printStackTrace(); } - //Traccar update Latitude Longitude + //enroll Traccar device if (status) { addDeviceToGroups(deviceIdentifier, device.getEnrolmentInfo().getOwnership()); @@ -568,14 +571,17 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceManagementDAOFactory.commitTransaction(); this.removeDeviceFromCache(deviceId); - //Traccar update Latitude Longitude + //disenroll Traccar device TraccarDevice traccarDeviceInfo = new TraccarDevice(device.getDeviceIdentifier()); DeviceAPIClientServiceImpl dac= new DeviceAPIClientServiceImpl(); - String deviceAPIClientResponse=dac.disDevice(traccarDeviceInfo); - if (log.isDebugEnabled()) { - log.debug("Disenroll Device "+ new Gson().toJson(deviceAPIClientResponse)); + try { + dac.disDevice(traccarDeviceInfo); + } catch (TraccarConfigurationException e) { + log.error("Error on Traccar disenroll a device" + e); + //e.printStackTrace(); } - //Traccar update Latitude Longitude + //disenroll Traccar device + } catch (DeviceManagementDAOException e) { DeviceManagementDAOFactory.rollbackTransaction(); String msg = "Error occurred while dis-enrolling '" + deviceId.getType() + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java index a96fff1f863..49084a800b1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java @@ -20,15 +20,36 @@ package org.wso2.carbon.device.mgt.core.traccar.api.service; 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.config.TraccarConfigurationException; -import java.io.IOException; public interface DeviceAPIClientService { - String updateLocation(TraccarPosition deviceInfo) throws IOException; + /** + * Create device Traccar configuration records + * + * @param deviceInfo to be added + * @throws TraccarConfigurationException errors thrown while creating a device traccar configuration + */ + void addDevice(TraccarDevice deviceInfo) throws TraccarConfigurationException; - String addDevice(TraccarDevice deviceInfo) throws IOException; + /** + * Add GPS location of a device Traccar configuration records + * + * @param deviceInfo to be added to update location of the device + * @throws TraccarConfigurationException errors thrown while inserting location of a device traccar configuration + */ + void updateLocation(TraccarPosition deviceInfo) throws TraccarConfigurationException; - String disDevice(TraccarDevice deviceInfo) throws IOException; + /** + * Delete a device Traccar configuration records + * + * @param deviceInfo to be delete a device + * @throws TraccarConfigurationException errors thrown while deleting a device traccar configuration + */ + void disDevice(TraccarDevice deviceInfo) throws TraccarConfigurationException; + + //String addGroup(TraccarGroups groupInfo) throws IOException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TrackerClient.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TrackerClient.java index 0cb7fc97c20..c2aec979a20 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TrackerClient.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TrackerClient.java @@ -19,7 +19,7 @@ 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; @@ -30,139 +30,195 @@ import org.apache.commons.logging.LogFactory; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; +import org.wso2.carbon.device.mgt.common.event.config.EventConfigurationException; import org.wso2.carbon.device.mgt.core.traccar.common.TraccarClient; import org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants; import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDevice; import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarPosition; +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.core.config.TraccarConfigurationManager; import java.io.IOException; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; import static org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants.ENDPOINT; import static org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants.AUTHORIZATION; import static org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants.AUTHORIZATION_KEY; -import static org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants.MAIN_ENDPOINT; public class TrackerClient implements TraccarClient { private static final Log log = LogFactory.getLog(TrackerClient.class); - - public Request getDeviceByDeviceIdentifier(String deviceId) { - //device identifier matches with traccar uniqueId - //Retrieve the traccar Gateway by passing the Gateway name - TraccarGateway traccarGateway = getTraccarGateway(); - - //Retrieve the properties in the Traccar Gateway by passing the property name - String endpoint = traccarGateway.getPropertyByName(MAIN_ENDPOINT).getValue(); - String authorization = traccarGateway.getPropertyByName(AUTHORIZATION).getValue(); - String authorizationKey = traccarGateway.getPropertyByName(AUTHORIZATION_KEY).getValue(); - - OkHttpClient client = new OkHttpClient().newBuilder().build(); - Request request = new Request.Builder() - .url(endpoint+"/devices?uniqueId="+deviceId) - .method("GET", null) - .addHeader(authorization, authorizationKey) + 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(ENDPOINT).getValue(); + final String authorization = traccarGateway.getPropertyByName(AUTHORIZATION).getValue(); + final String authorizationKey = traccarGateway.getPropertyByName(AUTHORIZATION_KEY).getValue(); + + public TrackerClient() { + client = new OkHttpClient.Builder() + .connectTimeout(30, TimeUnit.SECONDS) + .writeTimeout(30, TimeUnit.SECONDS) + .readTimeout(45, TimeUnit.SECONDS) + .connectionPool(new ConnectionPool(50,30,TimeUnit.SECONDS)) .build(); - return request; } - public String updateLocation(TraccarPosition deviceInfo) throws IOException { - //Retrieve the traccar Gateway by passing the Gateway name - TraccarGateway traccarGateway = getTraccarGateway(); - - //Retrieve the properties in the Traccar Gateway by passing the property name - String endpoint = traccarGateway.getPropertyByName(ENDPOINT).getValue(); + private class TrackerExecutor implements Runnable { + final JSONObject payload; + final String context; + final String publisherUrl; + private final String method; + + private TrackerExecutor(String publisherUrl, String context, JSONObject payload, String method) { + this.payload = payload; + this.context = context; + this.publisherUrl = publisherUrl; + this.method = method; + } - OkHttpClient client = new OkHttpClient().newBuilder().build(); - Request request = new Request.Builder() - .url(endpoint+"id="+deviceInfo.getDeviceIdentifier()+ - "×tamp="+deviceInfo.getTimestamp()+ - "&lat="+deviceInfo.getLat()+"&lon="+deviceInfo.getLon()+ - "&bearing="+deviceInfo.getBearing()+"&speed="+deviceInfo.getSpeed()+"&ignition=true") - .method("GET", null) - .build(); - Response response = client.newCall(request).execute(); - log.info(String.valueOf(response)); - return String.valueOf(response); + public void run() { + RequestBody requestBody; + Request.Builder builder = new Request.Builder(); + Request request; + + if(method=="post"){ + requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), payload.toString()); + builder = builder.post(requestBody); + }else if(method=="delete"){ + builder = builder.delete(); + } + + request = builder.url(publisherUrl + context) + .addHeader(authorization, authorizationKey) + .build(); + + try { + client.newCall(request).execute(); + if (log.isDebugEnabled()) { + log.debug("Successfully the request is proceed and communicated with Traccar"); + } + } catch (IOException e) { + log.error("Error occurred", e); + + } + } } - public String addDevice(TraccarDevice deviceInfo) throws IOException{ - //Retrieve the traccar Gateway by passing the Gateway name - TraccarGateway traccarGateway = getTraccarGateway(); - - //Retrieve the properties in the Traccar Gateway by passing the property name - String endpoint = traccarGateway.getPropertyByName(MAIN_ENDPOINT).getValue(); - String authorization = traccarGateway.getPropertyByName(AUTHORIZATION).getValue(); - String authorizationKey = traccarGateway.getPropertyByName(AUTHORIZATION_KEY).getValue(); - - OkHttpClient client = new OkHttpClient().newBuilder().build(); - MediaType mediaType = MediaType.parse("application/json"); - - JSONObject data = new JSONObject(); - data.put("name", deviceInfo.getDeviceName()); - data.put("uniqueId", deviceInfo.getUniqueId()); - data.put("status", deviceInfo.getStatus()); - data.put("disabled", deviceInfo.getDisabled()); - data.put("lastUpdate", deviceInfo.getLastUpdate()); - data.put("positionId", deviceInfo.getPositionId()); - data.put("groupId", deviceInfo.getGroupId()); - data.put("phone", deviceInfo.getPhone()); - data.put("model", deviceInfo.getModel()); - data.put("contact", deviceInfo.getContact()); - data.put("category", deviceInfo.getCategory()); - List geofenceIds = new ArrayList<>(); - data.put("geofenceIds", geofenceIds); - data.put("attributes", new JSONObject()); - - RequestBody body = RequestBody.create(mediaType, data.toString()); - Request request = new Request.Builder() - .url(endpoint+"/devices") - .method("POST", body) - .addHeader("Content-Type", "application/json") - .addHeader(authorization, authorizationKey) - .build(); - Response response = client.newCall(request).execute(); - - return String.valueOf(response); + /** + * Add Traccar Device operation. + * @param deviceInfo with DeviceName UniqueId, Status, Disabled LastUpdate, PositionId, GroupId + * Model, Contact, Category, fenceIds + * @throws TraccarConfigurationException Failed while add Traccar Device the operation + */ + public void addDevice(TraccarDevice deviceInfo) throws TraccarConfigurationException { + try{ + 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 geoFenceIds = new ArrayList<>(); + payload.put("geofenceIds", geoFenceIds); + payload.put("attributes", new JSONObject()); + String context = "8082/api/devices"; + Runnable trackerExecutor = new TrackerExecutor(endpoint, context, payload, "post"); + executor.execute(trackerExecutor); + log.info("Device successfully enorolled on traccar"); + }catch (Exception e){ + String msg="Could not enroll traccar device"; + log.error(msg, e); + throw new TraccarConfigurationException(msg, e); + } } - public String disDevice(TraccarDevice deviceInfo) throws IOException { - - //Retrieve the traccar Gateway by passing the Gateway name - TraccarGateway traccarGateway = getTraccarGateway(); - - //Retrieve the properties in the Traccar Gateway by passing the property name - String endpoint = traccarGateway.getPropertyByName(MAIN_ENDPOINT).getValue(); - String authorization = traccarGateway.getPropertyByName(AUTHORIZATION).getValue(); - String authorizationKey = traccarGateway.getPropertyByName(AUTHORIZATION_KEY).getValue(); + /** + * Add Device GPS Location operation. + * @param deviceInfo with DeviceIdentifier, Timestamp, Lat, Lon, Bearing, Speed, ignition + */ + public void updateLocation(TraccarPosition deviceInfo) throws TraccarConfigurationException { + try{ + String context = "5055/?id="+deviceInfo.getDeviceIdentifier()+"×tamp="+deviceInfo.getTimestamp()+ + "&lat="+deviceInfo.getLat()+"&lon="+deviceInfo.getLon()+"&bearing="+deviceInfo.getBearing()+ + "&speed="+deviceInfo.getSpeed()+"&ignition=true"; + Runnable trackerExecutor = new TrackerExecutor(endpoint, context, null, "get"); + executor.execute(trackerExecutor); + log.info("Device GPS location added on traccar"); + }catch (Exception e){ + String msg="Could not add GPS location"; + log.error(msg, e); + throw new TraccarConfigurationException(msg, e); + } + } - OkHttpClient client = new OkHttpClient(); - Request deviceDetails = getDeviceByDeviceIdentifier(deviceInfo.getDeviceIdentifier()); - Response response = client.newCall(deviceDetails).execute(); + /** + * Add Device GPS Location operation. + * @param deviceIdentifier + * @return device info + * @throws TraccarConfigurationException Failed while add Traccar Device location operation + */ + public String getDeviceByDeviceIdentifier(String deviceIdentifier) throws TraccarConfigurationException { + try { + String context = "8082/api/devices?uniqueId="+deviceIdentifier; + Runnable trackerExecutor = new TrackerExecutor(endpoint, context, null, "get"); + executor.execute(trackerExecutor); + Request request = new Request.Builder() + .url(endpoint+context) + .addHeader(authorization, authorizationKey) + .build(); + Response response = client.newCall(request).execute(); + String result = response.body().string(); + log.info("Device info found"); + return result; + } catch (IOException e) { + String msg="Could not find device information"; + log.error(msg, e); + throw new TraccarConfigurationException(msg, e); + } + } - String result = response.body().string(); - String jsonData ="{"+ "\"geodata\": "+ result+ "}"; + /** + * Dis-enroll a Device operation. + * @param deviceInfo identified via deviceIdentifier + * @throws TraccarConfigurationException Failed while dis-enroll a Traccar Device operation + */ + public void disDevice(TraccarDevice deviceInfo) throws TraccarConfigurationException { + try{ + String result = getDeviceByDeviceIdentifier(deviceInfo.getDeviceIdentifier()); + String jsonData ="{"+ "\"geodata\": "+ result+ "}"; - try { JSONObject obj = new JSONObject(jsonData); JSONArray geodata = obj.getJSONArray("geodata"); JSONObject jsonResponse = geodata.getJSONObject(0); - OkHttpClient client1 = new OkHttpClient(); - Request request1 = new Request.Builder() - .url(endpoint+"/devices/"+jsonResponse.getInt("id")).delete() - .addHeader(authorization, authorizationKey).build(); - Response response1 = client1.newCall(request1).execute(); - log.info(String.valueOf(response1)); - return String.valueOf(response1); - } catch (JSONException e) { - log.info("Delete Error "+e); - return String.valueOf(e); + String context = "8082/api/devices/"+jsonResponse.getInt("id"); + Runnable trackerExecutor = new TrackerExecutor(endpoint, context, null, "delete"); + executor.execute(trackerExecutor); + log.info("Device successfully dis-enrolled"); + }catch (JSONException e){ + String msg = "Could not find the device infomation to dis-enroll the device"; + log.error(msg, e); + throw new TraccarConfigurationException(msg); + }catch (TraccarConfigurationException ex){ + String msg = "Could not find the device infomation to dis-enroll the device"; + log.error(msg, ex); + throw new TraccarConfigurationException(msg, ex); } } - + private TraccarGateway getTraccarGateway(){ return TraccarConfigurationManager.getInstance().getTraccarConfig().getTraccarGateway( TraccarHandlerConstants.GATEWAY_NAME); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java index 5fb27e3be45..2cbbf57e5ea 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java @@ -19,27 +19,41 @@ package org.wso2.carbon.device.mgt.core.traccar.api.service.impl; +import org.wso2.carbon.device.mgt.common.event.config.EventMetaData; +import org.wso2.carbon.device.mgt.core.event.config.EventOperationExecutor; +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.traccar.api.service.DeviceAPIClientService; import org.wso2.carbon.device.mgt.core.traccar.api.service.addons.TrackerClient; 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.config.TraccarConfigurationException; import java.io.IOException; +import java.util.List; public class DeviceAPIClientServiceImpl implements DeviceAPIClientService { - public String updateLocation(TraccarPosition deviceInfo) throws IOException { + + public void addDevice(TraccarDevice deviceInfo) throws TraccarConfigurationException { TrackerClient client = new TrackerClient(); - return (client.updateLocation(deviceInfo)); + client.addDevice(deviceInfo); } - public String addDevice(TraccarDevice deviceInfo) throws IOException { + public void updateLocation(TraccarPosition deviceInfo) throws TraccarConfigurationException { TrackerClient client = new TrackerClient(); - return (client.addDevice(deviceInfo)); + client.updateLocation(deviceInfo); } - public String disDevice(TraccarDevice deviceInfo) throws IOException { + public void disDevice(TraccarDevice deviceInfo) throws TraccarConfigurationException { TrackerClient client = new TrackerClient(); - return (client.disDevice(deviceInfo)); + client.disDevice(deviceInfo); } + + /*public String addGroup(TraccarGroups groupInfo) throws IOException { + TrackerClient client = new TrackerClient(); + return (client.addGroup(groupInfo)); + }*/ + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarClient.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarClient.java index bf2092af76a..28c7ceaac15 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarClient.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarClient.java @@ -19,19 +19,21 @@ package org.wso2.carbon.device.mgt.core.traccar.common; -import okhttp3.Request; import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDevice; import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarPosition; +import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarConfigurationException; import java.io.IOException; public interface TraccarClient { - String updateLocation(TraccarPosition deviceInfo) throws IOException; + void addDevice(TraccarDevice deviceInfo) throws IOException, TraccarConfigurationException; - String addDevice(TraccarDevice deviceInfo) throws IOException; + void updateLocation(TraccarPosition deviceInfo) throws IOException, TraccarConfigurationException; - Request getDeviceByDeviceIdentifier(String deviceInfo) throws IOException; + String getDeviceByDeviceIdentifier(String deviceInfo) throws IOException, TraccarConfigurationException; - String disDevice(TraccarDevice deviceInfo) throws IOException; + void disDevice(TraccarDevice deviceInfo) throws TraccarConfigurationException, IOException; + + //String addGroup(TraccarGroups groupInfo) throws IOException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarHandlerConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarHandlerConstants.java index f1c4d6c5157..256ed44f30c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarHandlerConstants.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarHandlerConstants.java @@ -22,8 +22,7 @@ package org.wso2.carbon.device.mgt.core.traccar.common; public class TraccarHandlerConstants { public static final String TRACCAR_CONFIG_XML_NAME = "traccar-config.xml"; public static final String GATEWAY_NAME = "sample"; - public static final String MAIN_ENDPOINT = "api-endpoint"; - public static final String ENDPOINT = "add-location-api-endpoint"; + public static final String ENDPOINT = "api-endpoint"; public static final String AUTHORIZATION = "authorization"; public static final String AUTHORIZATION_KEY = "authorization-key"; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/TraccarConfigurationException.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/TraccarConfigurationException.java new file mode 100644 index 00000000000..748f6e0f79b --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/TraccarConfigurationException.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2020, 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. + */ + +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); + } +} From c18b3b1c1f08a04c72a1945ac70a56716a213135 Mon Sep 17 00:00:00 2001 From: Rushdi Date: Sat, 5 Mar 2022 01:13:37 +0530 Subject: [PATCH 04/41] Update the code structure --- .../impl/DeviceInformationManagerImpl.java | 15 ++-- .../internal/DeviceManagementDataHolder.java | 10 +++ .../DeviceManagementServiceComponent.java | 7 ++ .../DeviceManagementProviderService.java | 2 +- .../DeviceManagementProviderServiceImpl.java | 17 ++--- .../api/service/DeviceAPIClientService.java | 37 ++++++---- .../api/service/addons/TrackerClient.java | 36 ++++++++-- .../impl/DeviceAPIClientServiceImpl.java | 59 ---------------- .../impl/TraccarAPIClientServiceImpl.java | 68 +++++++++++++++++++ .../core/traccar/common/TraccarClient.java | 13 ++-- .../traccar/common/beans/TraccarDevice.java | 2 + 11 files changed, 159 insertions(+), 107 deletions(-) delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/TraccarAPIClientServiceImpl.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java index 19a6c64ef2c..e019716bdf4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java @@ -18,7 +18,6 @@ package org.wso2.carbon.device.mgt.core.device.details.mgt.impl; -import com.google.gson.Gson; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -44,15 +43,13 @@ import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsMgtDA import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.report.mgt.Constants; 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.beans.TraccarDevice; -import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarPosition; +import org.wso2.carbon.device.mgt.core.traccar.api.service.DeviceAPIClientService; +import org.wso2.carbon.device.mgt.core.traccar.api.service.impl.TraccarAPIClientServiceImpl; import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarConfigurationException; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil; import org.wso2.carbon.user.api.UserStoreException; -import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Calendar; @@ -393,12 +390,8 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { } //Traccar update GPS Location - TraccarPosition trackerinfo = new TraccarPosition(device.getDeviceIdentifier(), - deviceLocation.getUpdatedTime().getTime(), - deviceLocation.getLatitude(), deviceLocation.getLongitude(), - deviceLocation.getBearing(), deviceLocation.getSpeed()); - DeviceAPIClientServiceImpl dac= new DeviceAPIClientServiceImpl(); - dac.updateLocation(trackerinfo); + DeviceAPIClientService dac= DeviceManagementDataHolder.getInstance().getDeviceAPIClientService(); + dac.updateLocation(device, deviceLocation); //Traccar update GPS Location DeviceManagementDAOFactory.commitTransaction(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java index 5cb1a1c9ab6..6a69cb02ba5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java @@ -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.status.task.DeviceStatusTaskManagerService; 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.ntask.core.service.TaskService; import org.wso2.carbon.registry.core.service.RegistryService; @@ -83,6 +84,7 @@ public class DeviceManagementDataHolder { private GeoFenceEventOperationManager geoFenceEventOperationManager; private ExecutorService eventConfigExecutors; private OperationTimeoutTaskManagerService operationTimeoutTaskManagerService; + private DeviceAPIClientService deviceAPIClientService; private final Map deviceStatusTaskPluginConfigs = Collections.synchronizedMap( new HashMap<>()); @@ -349,4 +351,12 @@ public class DeviceManagementDataHolder { OperationTimeoutTaskManagerService operationTimeoutTaskManagerService) { this.operationTimeoutTaskManagerService = operationTimeoutTaskManagerService; } + + public DeviceAPIClientService getDeviceAPIClientService() { + return deviceAPIClientService; + } + + public void setDeviceAPIClientService(DeviceAPIClientService deviceAPIClientService) { + this.deviceAPIClientService = deviceAPIClientService; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java index 4c031163aa7..fec7cbcbf34 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java @@ -78,6 +78,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.GroupManagementProviderServiceImpl; 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.TraccarAPIClientServiceImpl; 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.DeviceMgtTenantMgtListener; @@ -302,6 +304,11 @@ public class DeviceManagementServiceComponent { DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(deviceManagementProvider); bundleContext.registerService(DeviceManagementProviderService.class.getName(), deviceManagementProvider, null); + /* Registering Device API Client Service */ + DeviceAPIClientService deviceAPIClientService = new TraccarAPIClientServiceImpl(); + DeviceManagementDataHolder.getInstance().setDeviceAPIClientService(deviceAPIClientService); + bundleContext.registerService(DeviceAPIClientService.class.getName(), deviceAPIClientService, null); + /* Registering Group Management Service */ GroupManagementProviderService groupManagementProvider = new GroupManagementProviderServiceImpl(); String defaultGroups = diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java index 4e283160594..851bb3050c9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java @@ -677,7 +677,7 @@ public interface DeviceManagementProviderService { boolean modifyEnrollment(Device device) throws DeviceManagementException; - boolean enrollDevice(Device device) throws DeviceManagementException, IOException; + boolean enrollDevice(Device device) throws DeviceManagementException; boolean saveConfiguration(PlatformConfiguration configuration) throws DeviceManagementException; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 20fa0406a44..845e335b404 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -118,9 +118,7 @@ import org.wso2.carbon.device.mgt.core.internal.PluginInitializationListener; import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataDAO; import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOFactory; import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; -import org.wso2.carbon.device.mgt.core.traccar.api.service.impl.DeviceAPIClientServiceImpl; -import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDevice; -import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarPosition; +import org.wso2.carbon.device.mgt.core.traccar.api.service.DeviceAPIClientService; import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarConfigurationException; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.email.sender.core.ContentProviderInfo; @@ -397,13 +395,9 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } //enroll Traccar device - String lastUpdatedTime = String.valueOf((new Date().getTime())); - TraccarDevice traccarDeviceInfo = new TraccarDevice(device.getName(), device.getDeviceIdentifier(), - "online", "false", lastUpdatedTime, "", "", "", "", - "", ""); - DeviceAPIClientServiceImpl dac= new DeviceAPIClientServiceImpl(); try { - dac.addDevice(traccarDeviceInfo); + DeviceAPIClientService dac= DeviceManagementDataHolder.getInstance().getDeviceAPIClientService(); + dac.addDevice(device); } catch (TraccarConfigurationException e) { log.error("Error on Traccar add device" + e); //e.printStackTrace(); @@ -572,10 +566,9 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv this.removeDeviceFromCache(deviceId); //disenroll Traccar device - TraccarDevice traccarDeviceInfo = new TraccarDevice(device.getDeviceIdentifier()); - DeviceAPIClientServiceImpl dac= new DeviceAPIClientServiceImpl(); try { - dac.disDevice(traccarDeviceInfo); + DeviceAPIClientService dac= DeviceManagementDataHolder.getInstance().getDeviceAPIClientService(); + dac.disDevice(device.getDeviceIdentifier()); } catch (TraccarConfigurationException e) { log.error("Error on Traccar disenroll a device" + e); //e.printStackTrace(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java index 49084a800b1..7ef5f777d0f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java @@ -19,37 +19,48 @@ package org.wso2.carbon.device.mgt.core.traccar.api.service; -import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDevice; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; +import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.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.config.TraccarConfigurationException; +import java.io.IOException; + public interface DeviceAPIClientService { /** - * Create device Traccar configuration records + * Add GPS location of a device Traccar configuration records * - * @param deviceInfo to be added - * @throws TraccarConfigurationException errors thrown while creating a device traccar configuration + * @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 addDevice(TraccarDevice deviceInfo) throws TraccarConfigurationException; + void updateLocation(Device device, DeviceLocation deviceLocation) throws TraccarConfigurationException; /** - * Add GPS location of a device Traccar configuration records + * Create device Traccar configuration records * - * @param deviceInfo to be added to update location of the device - * @throws TraccarConfigurationException errors thrown while inserting location of a device traccar configuration + * @param device to be added + * @throws TraccarConfigurationException errors thrown while creating a device traccar configuration */ - void updateLocation(TraccarPosition deviceInfo) throws TraccarConfigurationException; + void addDevice(Device device) throws TraccarConfigurationException; /** * Delete a device Traccar configuration records * - * @param deviceInfo to be delete a device + * @param deviceIdentifier to be delete a device * @throws TraccarConfigurationException errors thrown while deleting a device traccar configuration */ - void disDevice(TraccarDevice deviceInfo) throws TraccarConfigurationException; + void disDevice(String deviceIdentifier) throws TraccarConfigurationException; - //String addGroup(TraccarGroups groupInfo) throws IOException; + /** + * 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) throws TraccarConfigurationException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TrackerClient.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TrackerClient.java index c2aec979a20..62091212311 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TrackerClient.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TrackerClient.java @@ -30,10 +30,10 @@ import org.apache.commons.logging.LogFactory; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import org.wso2.carbon.device.mgt.common.event.config.EventConfigurationException; import org.wso2.carbon.device.mgt.core.traccar.common.TraccarClient; import org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants; import org.wso2.carbon.device.mgt.core.traccar.common.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.config.TraccarConfigurationException; import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarGateway; @@ -166,13 +166,14 @@ public class TrackerClient implements TraccarClient { /** * Add Device GPS Location operation. - * @param deviceIdentifier + * @param deviceId * @return device info * @throws TraccarConfigurationException Failed while add Traccar Device location operation */ - public String getDeviceByDeviceIdentifier(String deviceIdentifier) throws TraccarConfigurationException { + @Override + public String getDeviceByDeviceIdentifier(String deviceId) throws TraccarConfigurationException { try { - String context = "8082/api/devices?uniqueId="+deviceIdentifier; + String context = "8082/api/devices?uniqueId="+ deviceId; Runnable trackerExecutor = new TrackerExecutor(endpoint, context, null, "get"); executor.execute(trackerExecutor); Request request = new Request.Builder() @@ -200,6 +201,11 @@ public class TrackerClient implements TraccarClient { String result = getDeviceByDeviceIdentifier(deviceInfo.getDeviceIdentifier()); String jsonData ="{"+ "\"geodata\": "+ result+ "}"; + log.info("======================"); + log.info("result"); + log.info(result); + log.info(deviceInfo.getDeviceIdentifier()); + log.info("==========================="); JSONObject obj = new JSONObject(jsonData); JSONArray geodata = obj.getJSONArray("geodata"); JSONObject jsonResponse = geodata.getJSONObject(0); @@ -219,6 +225,28 @@ public class TrackerClient implements TraccarClient { } } + /** + * Add Traccar Device operation. + * @param groupInfo with groupName + * @throws TraccarConfigurationException Failed while add Traccar Device the operation + */ + public void addGroup(TraccarGroups groupInfo) throws TraccarConfigurationException { + try{ + JSONObject payload = new JSONObject(); + payload.put("name", groupInfo.getName()); + payload.put("attributes", new JSONObject()); + + String context = "8082/api/groups"; + Runnable trackerExecutor = new TrackerExecutor(endpoint, context, payload, "post"); + executor.execute(trackerExecutor); + log.info("Group successfully on traccar"); + }catch (Exception e){ + String msg="Could not add a traccar group"; + log.error(msg, e); + throw new TraccarConfigurationException(msg, e); + } + } + private TraccarGateway getTraccarGateway(){ return TraccarConfigurationManager.getInstance().getTraccarConfig().getTraccarGateway( TraccarHandlerConstants.GATEWAY_NAME); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java deleted file mode 100644 index 2cbbf57e5ea..00000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * 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.wso2.carbon.device.mgt.common.event.config.EventMetaData; -import org.wso2.carbon.device.mgt.core.event.config.EventOperationExecutor; -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.traccar.api.service.DeviceAPIClientService; -import org.wso2.carbon.device.mgt.core.traccar.api.service.addons.TrackerClient; -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.config.TraccarConfigurationException; - -import java.io.IOException; -import java.util.List; - -public class DeviceAPIClientServiceImpl implements DeviceAPIClientService { - - - public void addDevice(TraccarDevice deviceInfo) throws TraccarConfigurationException { - TrackerClient client = new TrackerClient(); - client.addDevice(deviceInfo); - } - - public void updateLocation(TraccarPosition deviceInfo) throws TraccarConfigurationException { - TrackerClient client = new TrackerClient(); - client.updateLocation(deviceInfo); - } - - public void disDevice(TraccarDevice deviceInfo) throws TraccarConfigurationException { - TrackerClient client = new TrackerClient(); - client.disDevice(deviceInfo); - } - - /*public String addGroup(TraccarGroups groupInfo) throws IOException { - TrackerClient client = new TrackerClient(); - return (client.addGroup(groupInfo)); - }*/ - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/TraccarAPIClientServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/TraccarAPIClientServiceImpl.java new file mode 100644 index 00000000000..a64cf6d31be --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/TraccarAPIClientServiceImpl.java @@ -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.api.service.impl; + +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; +import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; +import org.wso2.carbon.device.mgt.core.traccar.api.service.DeviceAPIClientService; +import org.wso2.carbon.device.mgt.core.traccar.api.service.addons.TrackerClient; +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.config.TraccarConfigurationException; + +import java.util.Date; + +public class TraccarAPIClientServiceImpl implements DeviceAPIClientService { + + + public void addDevice(Device device) throws TraccarConfigurationException { + TrackerClient client = new TrackerClient(); + String lastUpdatedTime = String.valueOf((new Date().getTime())); + TraccarDevice traccarDeviceInfo = new TraccarDevice(device.getName(), device.getDeviceIdentifier(), + "online", "false", lastUpdatedTime, "", "", "", "", + "", ""); + client.addDevice(traccarDeviceInfo); + } + + public void updateLocation(Device device, DeviceLocation deviceLocation) throws TraccarConfigurationException { + TrackerClient client = new TrackerClient(); + TraccarPosition traccarPosition = new TraccarPosition(device.getDeviceIdentifier(), + deviceLocation.getUpdatedTime().getTime(), + deviceLocation.getLatitude(), deviceLocation.getLongitude(), + deviceLocation.getBearing(), deviceLocation.getSpeed()); + client.updateLocation(traccarPosition); + } + + public void disDevice(String deviceIdentifier) throws TraccarConfigurationException { + TrackerClient client = new TrackerClient(); + TraccarDevice traccarDeviceInfo = new TraccarDevice(deviceIdentifier); + client.disDevice(traccarDeviceInfo); + } + + public void addGroup(DeviceGroup group) throws TraccarConfigurationException { + TrackerClient client = new TrackerClient(); + TraccarGroups traccarGroups = new TraccarGroups(group.getName()); + client.addGroup(traccarGroups); + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarClient.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarClient.java index 28c7ceaac15..abac0303d31 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarClient.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarClient.java @@ -20,20 +20,19 @@ package org.wso2.carbon.device.mgt.core.traccar.common; 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.config.TraccarConfigurationException; -import java.io.IOException; - public interface TraccarClient { - void addDevice(TraccarDevice deviceInfo) throws IOException, TraccarConfigurationException; + void addDevice(TraccarDevice deviceInfo) throws TraccarConfigurationException; - void updateLocation(TraccarPosition deviceInfo) throws IOException, TraccarConfigurationException; + void updateLocation(TraccarPosition deviceInfo) throws TraccarConfigurationException; - String getDeviceByDeviceIdentifier(String deviceInfo) throws IOException, TraccarConfigurationException; + String getDeviceByDeviceIdentifier(String deviceId) throws TraccarConfigurationException; - void disDevice(TraccarDevice deviceInfo) throws TraccarConfigurationException, IOException; + void disDevice(TraccarDevice deviceInfo) throws TraccarConfigurationException; - //String addGroup(TraccarGroups groupInfo) throws IOException; + void addGroup(TraccarGroups groupInfo) throws TraccarConfigurationException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarDevice.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarDevice.java index 29b4bc50098..07793340769 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarDevice.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarDevice.java @@ -19,6 +19,8 @@ package org.wso2.carbon.device.mgt.core.traccar.common.beans; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; + public class TraccarDevice { private String deviceIdentifier; private String deviceName; From 2e5a9002da6a5612801e090b7da3a3eee5e2bd58 Mon Sep 17 00:00:00 2001 From: Rushdi Date: Tue, 8 Mar 2022 21:58:08 +0530 Subject: [PATCH 05/41] Update traccar configuration --- .../config/operation/traccar-config.xml | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/operation/traccar-config.xml diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/operation/traccar-config.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/operation/traccar-config.xml new file mode 100644 index 00000000000..2072aca2371 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/operation/traccar-config.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + sample + http://localhost: + 8085 + 5055 + Authorization + Basic YWRtaW46YWRtaW4= + + + + From 1dd2e35f89e018e4ef1af3188e7100938923e3d7 Mon Sep 17 00:00:00 2001 From: Rushdi Date: Tue, 8 Mar 2022 22:05:17 +0530 Subject: [PATCH 06/41] Update traccar cofiguration --- .../org.wso2.carbon.device.mgt.core/pom.xml | 12 +----- .../impl/DeviceInformationManagerImpl.java | 13 +++---- .../DeviceManagementProviderServiceImpl.java | 13 +++---- .../api/service/addons/TrackerClient.java | 16 +++++--- .../impl/TraccarAPIClientServiceImpl.java | 2 - .../common/TraccarHandlerConstants.java | 2 + .../traccar/common/beans/TraccarGroups.java | 39 +++++++++++++++++++ .../config/operation/traccar-config.xml | 2 +- 8 files changed, 64 insertions(+), 35 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarGroups.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml index d5618ef1d84..3a8962b6023 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml @@ -343,18 +343,8 @@ guava - com.fasterxml.jackson.core - jackson-databind - 2.11.2 - - - io.github.openfeign - feign-okhttp - - - org.wso2.orbit.com.squareup.okhttp + com.squareup.okhttp3 okhttp - 4.2.0.wso2v1 compile diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java index e019716bdf4..57e672bd622 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java @@ -43,8 +43,6 @@ import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsMgtDA import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.report.mgt.Constants; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; -import org.wso2.carbon.device.mgt.core.traccar.api.service.DeviceAPIClientService; -import org.wso2.carbon.device.mgt.core.traccar.api.service.impl.TraccarAPIClientServiceImpl; import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarConfigurationException; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil; @@ -390,8 +388,12 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { } //Traccar update GPS Location - DeviceAPIClientService dac= DeviceManagementDataHolder.getInstance().getDeviceAPIClientService(); - dac.updateLocation(device, deviceLocation); + try { + DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() + .updateLocation(device, deviceLocation); + } catch (TraccarConfigurationException e) { + log.error("Error on Traccar while adding GEO Location" + e); + } //Traccar update GPS Location DeviceManagementDAOFactory.commitTransaction(); @@ -407,9 +409,6 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { // } catch (DataPublisherConfigurationException e) { // DeviceManagementDAOFactory.rollbackTransaction(); // throw new DeviceDetailsMgtException("Error occurred while publishing the device location information.", e); - } catch (TraccarConfigurationException e) { - log.error("Error on Traccar" + e); - //e.printStackTrace(); } finally { DeviceManagementDAOFactory.closeConnection(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 845e335b404..bd7e2ebb509 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -396,11 +396,9 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv //enroll Traccar device try { - DeviceAPIClientService dac= DeviceManagementDataHolder.getInstance().getDeviceAPIClientService(); - dac.addDevice(device); + DeviceManagementDataHolder.getInstance().getDeviceAPIClientService().addDevice(device); } catch (TraccarConfigurationException e) { - log.error("Error on Traccar add device" + e); - //e.printStackTrace(); + log.error("Error while adding a device to traccar " + e); } //enroll Traccar device @@ -567,11 +565,10 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv //disenroll Traccar device try { - DeviceAPIClientService dac= DeviceManagementDataHolder.getInstance().getDeviceAPIClientService(); - dac.disDevice(device.getDeviceIdentifier()); + DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() + .disDevice(device.getDeviceIdentifier()); } catch (TraccarConfigurationException e) { - log.error("Error on Traccar disenroll a device" + e); - //e.printStackTrace(); + log.error("Error while disenrolling a device from Traccar " + e); } //disenroll Traccar device diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TrackerClient.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TrackerClient.java index 62091212311..4d4f7ada436 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TrackerClient.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TrackerClient.java @@ -49,6 +49,8 @@ import java.util.concurrent.TimeUnit; import static org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants.ENDPOINT; import static org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants.AUTHORIZATION; import static org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants.AUTHORIZATION_KEY; +import static org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants.DEFAULT_PORT; +import static org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants.LOCATION_UPDATE_PORT; public class TrackerClient implements TraccarClient { private static final Log log = LogFactory.getLog(TrackerClient.class); @@ -60,6 +62,8 @@ public class TrackerClient implements TraccarClient { final String endpoint = traccarGateway.getPropertyByName(ENDPOINT).getValue(); final String authorization = traccarGateway.getPropertyByName(AUTHORIZATION).getValue(); final String authorizationKey = traccarGateway.getPropertyByName(AUTHORIZATION_KEY).getValue(); + final String defaultPort = traccarGateway.getPropertyByName(DEFAULT_PORT).getValue(); + final String locationUpdatePort = traccarGateway.getPropertyByName(LOCATION_UPDATE_PORT).getValue(); public TrackerClient() { client = new OkHttpClient.Builder() @@ -89,7 +93,7 @@ public class TrackerClient implements TraccarClient { Request request; if(method=="post"){ - requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), payload.toString()); + requestBody = RequestBody.create(payload.toString(), MediaType.parse("application/json; charset=utf-8")); builder = builder.post(requestBody); }else if(method=="delete"){ builder = builder.delete(); @@ -134,7 +138,7 @@ public class TrackerClient implements TraccarClient { List geoFenceIds = new ArrayList<>(); payload.put("geofenceIds", geoFenceIds); payload.put("attributes", new JSONObject()); - String context = "8082/api/devices"; + String context = defaultPort+"/api/devices"; Runnable trackerExecutor = new TrackerExecutor(endpoint, context, payload, "post"); executor.execute(trackerExecutor); log.info("Device successfully enorolled on traccar"); @@ -151,7 +155,7 @@ public class TrackerClient implements TraccarClient { */ public void updateLocation(TraccarPosition deviceInfo) throws TraccarConfigurationException { try{ - String context = "5055/?id="+deviceInfo.getDeviceIdentifier()+"×tamp="+deviceInfo.getTimestamp()+ + String context = locationUpdatePort+"/?id="+deviceInfo.getDeviceIdentifier()+"×tamp="+deviceInfo.getTimestamp()+ "&lat="+deviceInfo.getLat()+"&lon="+deviceInfo.getLon()+"&bearing="+deviceInfo.getBearing()+ "&speed="+deviceInfo.getSpeed()+"&ignition=true"; Runnable trackerExecutor = new TrackerExecutor(endpoint, context, null, "get"); @@ -173,7 +177,7 @@ public class TrackerClient implements TraccarClient { @Override public String getDeviceByDeviceIdentifier(String deviceId) throws TraccarConfigurationException { try { - String context = "8082/api/devices?uniqueId="+ deviceId; + String context = defaultPort+"/api/devices?uniqueId="+ deviceId; Runnable trackerExecutor = new TrackerExecutor(endpoint, context, null, "get"); executor.execute(trackerExecutor); Request request = new Request.Builder() @@ -210,7 +214,7 @@ public class TrackerClient implements TraccarClient { JSONArray geodata = obj.getJSONArray("geodata"); JSONObject jsonResponse = geodata.getJSONObject(0); - String context = "8082/api/devices/"+jsonResponse.getInt("id"); + String context = defaultPort+"/api/devices/"+jsonResponse.getInt("id"); Runnable trackerExecutor = new TrackerExecutor(endpoint, context, null, "delete"); executor.execute(trackerExecutor); log.info("Device successfully dis-enrolled"); @@ -236,7 +240,7 @@ public class TrackerClient implements TraccarClient { payload.put("name", groupInfo.getName()); payload.put("attributes", new JSONObject()); - String context = "8082/api/groups"; + String context = defaultPort+"/api/groups"; Runnable trackerExecutor = new TrackerExecutor(endpoint, context, payload, "post"); executor.execute(trackerExecutor); log.info("Group successfully on traccar"); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/TraccarAPIClientServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/TraccarAPIClientServiceImpl.java index a64cf6d31be..eac0c63b985 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/TraccarAPIClientServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/TraccarAPIClientServiceImpl.java @@ -20,7 +20,6 @@ package org.wso2.carbon.device.mgt.core.traccar.api.service.impl; import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.core.traccar.api.service.DeviceAPIClientService; @@ -34,7 +33,6 @@ import java.util.Date; public class TraccarAPIClientServiceImpl implements DeviceAPIClientService { - public void addDevice(Device device) throws TraccarConfigurationException { TrackerClient client = new TrackerClient(); String lastUpdatedTime = String.valueOf((new Date().getTime())); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarHandlerConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarHandlerConstants.java index 256ed44f30c..b4b2ba0e2d7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarHandlerConstants.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarHandlerConstants.java @@ -25,4 +25,6 @@ public class TraccarHandlerConstants { 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"; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarGroups.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarGroups.java new file mode 100644 index 00000000000..b82496980a8 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarGroups.java @@ -0,0 +1,39 @@ +/* + * 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; + + public TraccarGroups(String name){ + this.name =name; + } + + public TraccarGroups(){ } + + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/operation/traccar-config.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/operation/traccar-config.xml index 2072aca2371..67de666e5e2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/operation/traccar-config.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/operation/traccar-config.xml @@ -1,7 +1,7 @@ diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerPermissionInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerPermissionInfo.java new file mode 100644 index 00000000000..cb91e44bcf9 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerPermissionInfo.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.device.mgt.common; + +import java.io.Serializable; + +public class 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; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerUserInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerUserInfo.java new file mode 100644 index 00000000000..96d5c5137ed --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerUserInfo.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.device.mgt.common; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; + +@ApiModel(value = "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; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerDAO.java index 44e42120a7a..6deffa8846f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerDAO.java @@ -20,6 +20,7 @@ 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; public interface TrackerDAO { @@ -90,6 +91,24 @@ public interface TrackerDAO { */ int removeTrackerGroup(int id) throws TrackerManagementDAOException; + /** + * give permission to a user to view traccar device. + * @param traccarUserId mapping table. + * @param deviceId mapping table. + * @throws TrackerManagementDAOException + */ + Boolean addTrackerUssrDevicePermission(int traccarUserId, int deviceId) throws TrackerManagementDAOException; + + /** + * Remove a permission on viewing a device. + * @param traccarUserId mapping table. + * @param deviceId mapping table. + * @throws TrackerManagementDAOException + */ + Boolean removeTrackerUssrDevicePermission(int traccarUserId, int deviceId) throws TrackerManagementDAOException; + + TrackerPermissionInfo getUserIdofPermissionByDeviceId(int deviceId) throws TrackerManagementDAOException; + /** * get trackerGroup info. * @param groupId of the device. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/tracker/TrackerDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/tracker/TrackerDAOImpl.java index 18a4d13f9f4..aad9ba8b085 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/tracker/TrackerDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/tracker/TrackerDAOImpl.java @@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.core.dao.impl.tracker; import org.wso2.carbon.device.mgt.common.TrackerDeviceInfo; import org.wso2.carbon.device.mgt.common.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; @@ -214,6 +215,68 @@ public class TrackerDAOImpl implements TrackerDAO { } } + @Override + public Boolean addTrackerUssrDevicePermission(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) { + throw new TrackerManagementDAOException("Error occurred while adding traccar user device mapping", e); + } finally { + TrackerManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public Boolean removeTrackerUssrDevicePermission(int traccarUserId, int deviceId) throws TrackerManagementDAOException { + PreparedStatement stmt = null; + try { + Connection conn = TrackerManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_EXT_PERMISSION_MAPPING WHERE TRACCAR_USER_ID=? AND TRACCAR_DEVICE_ID=?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, traccarUserId); + stmt.setInt(2, deviceId); + stmt.execute(); + + return true; + } catch (SQLException e) { + throw new TrackerManagementDAOException("Error occurred while removing traccar user device permission mapping", e); + } finally { + TrackerManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public TrackerPermissionInfo getUserIdofPermissionByDeviceId(int deviceId) throws TrackerManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + TrackerPermissionInfo trackerPermissionInfo = null; + try { + Connection conn = TrackerManagementDAOFactory.getConnection(); + String sql = "SELECT TRACCAR_DEVICE_ID, TRACCAR_USER_ID FROM DM_EXT_PERMISSION_MAPPING WHERE " + + "TRACCAR_DEVICE_ID = ? ORDER BY TRACCAR_DEVICE_ID DESC LIMIT 1"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, deviceId); + rs = stmt.executeQuery(); + if (rs.next()) { + trackerPermissionInfo = this.loadPermission(rs); + } + return trackerPermissionInfo; + } catch (SQLException e) { + throw new TrackerManagementDAOException("Error occurred while retrieving the traccar group information ", e); + } finally { + TrackerManagementDAOUtil.cleanupResources(stmt, rs); + } + } + + private TrackerGroupInfo loadTrackerGroup(ResultSet rs) throws SQLException { TrackerGroupInfo trackerGroupInfo = new TrackerGroupInfo(); trackerGroupInfo.setId(rs.getInt("ID")); @@ -233,4 +296,11 @@ public class TrackerDAOImpl implements TrackerDAO { trackerDeviceInfo.setStatus(rs.getInt("STATUS")); return trackerDeviceInfo; } + + private TrackerPermissionInfo loadPermission(ResultSet rs) throws SQLException { + TrackerPermissionInfo trackerPermissionInfo = new TrackerPermissionInfo(); + trackerPermissionInfo.setTraccarUserId(rs.getInt("TRACCAR_USER_ID")); + trackerPermissionInfo.setTraccarDeviceId(rs.getInt("TRACCAR_DEVICE_ID")); + return trackerPermissionInfo; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java index 53a833785bf..438f118b2d8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java @@ -53,6 +53,7 @@ import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.ExecutionException; public class DeviceInformationManagerImpl implements DeviceInformationManager { @@ -388,8 +389,16 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { //Tracker update GPS Location if (HttpReportingUtil.isLocationPublishing() && HttpReportingUtil.isTrackerEnabled()) { - DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() - .updateLocation(device, deviceLocation, CarbonContext.getThreadLocalCarbonContext().getTenantId()); + 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); + } } //Tracker update GPS Location diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 7a62186377a..4488f4da3ad 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -160,6 +160,17 @@ import java.text.Format; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.TimeUnit; +import java.util.ArrayList; +import java.util.Calendar; +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.ExecutionException; import java.util.stream.Collectors; @@ -412,7 +423,15 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv //enroll Traccar device if (HttpReportingUtil.isTrackerEnabled()) { - DeviceManagementDataHolder.getInstance().getDeviceAPIClientService().addDevice(device, tenantId); + try { + DeviceManagementDataHolder.getInstance().getDeviceAPIClientService().addDevice(device, tenantId); + } catch (ExecutionException e) { + log.error("ExecutionException : " + e); + //throw new RuntimeException(e); + } catch (InterruptedException e) { + log.error("InterruptedException : " + e); + //throw new RuntimeException(e); + } } //enroll Traccar device @@ -581,7 +600,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv //procees to dis-enroll a device from traccar starts if (HttpReportingUtil.isTrackerEnabled()) { DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() - .disEndrollDevice(device.getId(), tenantId); + .disEnrollDevice(device.getId(), tenantId); } //procees to dis-enroll a device from traccar ends diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java index 99af81e5a99..28511f28685 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java @@ -21,9 +21,12 @@ 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 { /** @@ -33,7 +36,7 @@ public interface DeviceAPIClientService { * @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); + void updateLocation(Device device, DeviceLocation deviceLocation, int tenantId) throws ExecutionException, InterruptedException; /** * Create device Traccar configuration records @@ -41,15 +44,7 @@ public interface DeviceAPIClientService { * @param device to be added * @throws TraccarConfigurationException errors thrown while creating a device traccar configuration */ - void addDevice(Device device, int tenantId); - - /** - * Create device Traccar configuration records - * - * @param device to modify - * @throws TraccarConfigurationException errors thrown while creating a device traccar configuration - */ - void updateDevice(Device device, int tenantId); + void addDevice(Device device, int tenantId) throws ExecutionException, InterruptedException; /** * Delete a device Traccar configuration records @@ -57,7 +52,7 @@ public interface DeviceAPIClientService { * @param deviceId to be delete a device * @throws TraccarConfigurationException errors thrown while deleting a device traccar configuration */ - void disEndrollDevice(int deviceId, int tenantId); + void disEnrollDevice(int deviceId, int tenantId); /** * Delete a device Traccar configuration records @@ -65,7 +60,7 @@ public interface DeviceAPIClientService { * @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); + void addGroup(DeviceGroup group, int groupID, int tenantId) throws TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException; /** * Delete a device Traccar configuration records @@ -73,7 +68,7 @@ public interface DeviceAPIClientService { * @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); + void updateGroup(DeviceGroup group, int groupID, int tenantId) throws ExecutionException, InterruptedException, TraccarConfigurationException, TrackerAlreadyExistException; /** * Delete a device Traccar configuration records @@ -82,5 +77,5 @@ public interface DeviceAPIClientService { * @param tenantId to delete a group * @throws TraccarConfigurationException errors thrown while adding a group traccar configuration */ - void deleteGroup(int groupId, int tenantId); + void deleteGroup(int groupId, int tenantId) throws ExecutionException, InterruptedException, TraccarConfigurationException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/TraccarClient.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/TraccarClient.java index 1be320687b2..c44162a30a0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/TraccarClient.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/TraccarClient.java @@ -27,33 +27,39 @@ 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.concurrent.ExecutionException; + public interface TraccarClient { - void addDevice(TraccarDevice deviceInfo, int tenantId) throws - TraccarConfigurationException, TrackerAlreadyExistException; + String fetchAllDevices() throws TraccarConfigurationException, ExecutionException, InterruptedException; - void updateDevice(TraccarDevice deviceInfo, int tenantId) throws - TraccarConfigurationException, TrackerAlreadyExistException; + void addDevice(TraccarDevice deviceInfo, int tenantId) throws + TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException; void updateLocation(TraccarDevice device, TraccarPosition deviceInfo, int tenantId) throws - TraccarConfigurationException, TrackerAlreadyExistException; + TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException; - void disEndrollDevice(int traccarDeviceId, int tenantId) throws TraccarConfigurationException; + void disEnrollDevice(int traccarDeviceId, int tenantId) throws TraccarConfigurationException; void addGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws - TraccarConfigurationException, TrackerAlreadyExistException; + TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException; void updateGroup(TraccarGroups groupInfo, int groupId, int tenantId) - throws TraccarConfigurationException, TrackerAlreadyExistException; + throws TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException; + + void deleteGroup(int traccarGroupId, int tenantId) throws TraccarConfigurationException, ExecutionException, InterruptedException; + + void setPermission(int userId, int deviceId) throws TraccarConfigurationException, ExecutionException, InterruptedException; - void deleteGroup(int traccarGroupId, int tenantId) throws TraccarConfigurationException; + void removePermission(int userId, int deviceId) throws TraccarConfigurationException, ExecutionException, InterruptedException; - void fetchAllUsers(String createUser, TraccarUser traccarUser, int deviceId) throws TraccarConfigurationException; + String fetchAllUsers() throws TraccarConfigurationException, ExecutionException, InterruptedException; - void createUser(TraccarUser traccarUser, String method, int deviceId) throws TraccarConfigurationException; + String fetchUserInfo(String userName) throws TraccarConfigurationException, ExecutionException, InterruptedException; - void updateUser(JSONObject traccarUser) throws TraccarConfigurationException; + String createUser(TraccarUser traccarUser) throws ExecutionException, InterruptedException; - void setPermission(int userId, int deviceId) throws TraccarConfigurationException; + String updateUser(TraccarUser traccarUser, int userId) throws ExecutionException, InterruptedException; + String returnUser(String userName) throws TraccarConfigurationException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java index 078dbef2dc1..e24e855ae61 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java @@ -29,17 +29,18 @@ import okhttp3.Response; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONArray; -import org.json.JSONException; 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; @@ -47,16 +48,20 @@ 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 java.io.IOException; import java.sql.SQLException; -import java.util.ArrayList; +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 { @@ -79,246 +84,240 @@ public class TraccarClientImpl implements TraccarClient { .connectTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) .readTimeout(45, TimeUnit.SECONDS) - .connectionPool(new ConnectionPool(50,30,TimeUnit.SECONDS)) + .connectionPool(new ConnectionPool(100,50,TimeUnit.SECONDS)) .build(); this.trackerDAO = TrackerManagementDAOFactory.getTrackerDAO(); } - private class TrackerExecutor implements Runnable { - final int deviceId; - final int groupId; - final int tenantId; + private class OkHttpClientThreadPool implements Callable { + final String publisherUrlWithContext; final JSONObject payload; - final String context; - final String publisherUrl; private final String method; - private final String type; - private TrackerExecutor(int id, int tenantId, String publisherUrl, String context, JSONObject payload, - String method, String type) { - this.deviceId = id; - this.groupId = id; - this.tenantId = tenantId; + private OkHttpClientThreadPool(String publisherUrlWithContext, JSONObject payload, String method) { + this.publisherUrlWithContext = publisherUrlWithContext; this.payload = payload; - this.context = context; - this.publisherUrl = publisherUrl; this.method = method; - this.type = type; } - public void run() { + @Override + public String call() throws Exception { RequestBody requestBody; Request.Builder builder = new Request.Builder(); Request request; Response response; - if(method==TraccarHandlerConstants.Methods.POST){ + 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(method==TraccarHandlerConstants.Methods.PUT){ + }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(method==TraccarHandlerConstants.Methods.DELETE){ + }else if(Objects.equals(method, TraccarHandlerConstants.Methods.DELETE)){ builder = builder.delete(); } - request = builder.url(publisherUrl + context).addHeader(authorization, authorizationKey).build(); + request = builder.url(endpoint+publisherUrlWithContext).addHeader(authorization, authorizationKey).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 result = executor.submit(new OkHttpClientThreadPool(url, null, method)); + String res = result.get(); + //executor.shutdown(); + return res; + } - try { - response = client.newCall(request).execute(); - if(method==TraccarHandlerConstants.Methods.POST){ - String result = response.body().string(); - log.info(result); - if(type==TraccarHandlerConstants.Types.PERMISSION){ - String msg =""; - if(result == ""){ - msg ="Successfully the device is assigned to the user"; - }else{ - msg = "Error occurred while fetching users ."; - } - log.info(msg); - }else if(result.charAt(0)=='{'){ - JSONObject obj = new JSONObject(result); - if (obj.has("id")){ - int traccarId = obj.getInt("id"); - try { - TrackerManagementDAOFactory.beginTransaction(); - if(type==TraccarHandlerConstants.Types.DEVICE){ - trackerDAO.addTrackerDevice(traccarId, deviceId, tenantId); - TrackerDeviceInfo res = trackerDAO.getTrackerDevice(deviceId, tenantId); - if(res.getStatus()==0){ - trackerDAO.updateTrackerDeviceIdANDStatus(res.getTraccarDeviceId(), deviceId, tenantId, 1); - - TraccarUser traccarUser = new TraccarUser(); - traccarUser.setName(username); - traccarUser.setLogin(username); - traccarUser.setEmail(username); - traccarUser.setPassword(generateRandomString(10)); - traccarUser.setToken(generateRandomString(32)); - traccarUser.setDeviceLimit(-1); - - log.info("============================="); - log.info(new Gson().toJson(traccarUser)); - log.info("============================="); - //device is available - //device is not available - //user is available - //user is not available - fetchAllUsers(TraccarHandlerConstants.Types.USER_CREATE_WITH_INSERT_DEVICE, traccarUser, traccarId); - } - }else if(type==TraccarHandlerConstants.Types.GROUP){ - trackerDAO.addTrackerGroup(traccarId, groupId, tenantId); - TrackerGroupInfo res = trackerDAO.getTrackerGroup(groupId, tenantId); - if(res.getStatus()==0){ - trackerDAO.updateTrackerGroupIdANDStatus(res.getTraccarGroupId(), groupId, tenantId, 1); - } - }else if(type==TraccarHandlerConstants.Types.USER_CREATE){ - log.info("============="); - log.info("User inserted"); - log.info("============="); - }else if(type==TraccarHandlerConstants.Types.USER_CREATE_WITH_INSERT_DEVICE){ - int userId = traccarId; - log.info("============="); - log.info("User inserted and setting to create session"); - log.info("============="); - setPermission(userId, deviceId); - } - TrackerManagementDAOFactory.commitTransaction(); - } catch (JSONException e) { - TrackerManagementDAOFactory.rollbackTransaction(); - String msg = "Error occurred on JSON object ."; - log.error(msg, e); - } catch (TransactionManagementException e) { - TrackerManagementDAOFactory.rollbackTransaction(); - String msg = "Error occurred establishing the DB connection ."; - log.error(msg, e); - } catch (TrackerManagementDAOException e) { - TrackerManagementDAOFactory.rollbackTransaction(); - String msg = null; - if(type==TraccarHandlerConstants.Types.DEVICE){ - msg = "Already device with deviceId " + deviceId + " exists" ; - }else if(type==TraccarHandlerConstants.Types.GROUP){ - msg = "Already the group with groupId - " + groupId + " exists!"; - }else if(type==TraccarHandlerConstants.Types.USER){ - msg = "Error occurred while fetching users."; - }else if(type==TraccarHandlerConstants.Types.PERMISSION){ - msg = "Error occurred while assigning the device to the user." + traccarId + deviceId; - } - log.error(msg, e); - } finally { - TrackerManagementDAOFactory.closeConnection(); - } - } - response.close(); - } - if (log.isDebugEnabled()) { - log.debug("Successfully the request is proceed and communicated with Traccar"); - } - }else if(method==TraccarHandlerConstants.Methods.GET){ - if(type!=TraccarHandlerConstants.Types.DEVICE){ - response = client.newCall(request).execute(); - String result = response.body().string(); - - JSONArray fetchAllUsers = new JSONArray(result); - int userAvailability = 0; - int userId = 0; - for(int i=0; i res = executor.submit(new OkHttpClientThreadPool(url, payload, method)); + 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); - } catch (IOException | TraccarConfigurationException e) { - log.error("Couldnt connect to traccar.", e); + Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method)); + String result = res.get(); + //executor.shutdown(); + return result; + } + + public void setPermission(int userId, int deviceId) throws TraccarConfigurationException, ExecutionException, InterruptedException { + JSONObject payload = new JSONObject(); + payload.put("userId", userId); + payload.put("deviceId", deviceId); + + String method = TraccarHandlerConstants.Methods.POST; + String url = defaultPort+"/api/permissions"; + + Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method)); + String result = res.get(); + //executor.shutdown(); + + if(result!=null){ + try { + TrackerManagementDAOFactory.beginTransaction(); + trackerDAO.addTrackerUssrDevicePermission(userId, deviceId); + 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(); } } } - /** - * Add Traccar Device operation. - * @param deviceInfo with DeviceName UniqueId, Status, Disabled LastUpdate, PositionId, GroupId - * Model, Contact, Category, fenceIds - * @throws TraccarConfigurationException Failed while add Traccar Device the operation - */ - public void addDevice(TraccarDevice deviceInfo, int tenantId) throws TraccarConfigurationException, TrackerAlreadyExistException { - TrackerDeviceInfo res = null; - try { - TrackerManagementDAOFactory.openConnection(); - res = trackerDAO.getTrackerDevice(deviceInfo.getId(), tenantId); - if(res!=null){ - String msg = "The device already exit"; - log.error(msg); - throw new TrackerAlreadyExistException(msg); + public void removePermission(int userId, int deviceId) throws TraccarConfigurationException, 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 res = executor.submit(new OkHttpClientThreadPool(url, payload, method)); + String result = res.get(); + //executor.shutdown(); + + if(result!=null){ + try { + TrackerManagementDAOFactory.beginTransaction(); + trackerDAO.removeTrackerUssrDevicePermission(userId, deviceId); + 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(); } - } catch (TrackerManagementDAOException e) { - String msg = "Error occurred while mapping with deviceId ."; - 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(); } + } + + public String fetchAllDevices() throws ExecutionException, InterruptedException { + String method = TraccarHandlerConstants.Methods.GET; + String url = defaultPort+"/api/devices"; - JSONObject payload = payload(deviceInfo); - String context = defaultPort+"/api/devices"; - Runnable trackerExecutor = new TrackerExecutor(deviceInfo.getId(), tenantId, endpoint, context, payload, - TraccarHandlerConstants.Methods.POST, TraccarHandlerConstants.Types.DEVICE); - executor.execute(trackerExecutor); + Future result = executor.submit(new OkHttpClientThreadPool(url, null, method)); + String res = result.get(); + //executor.shutdown(); + return res; } /** - * update Traccar Device operation. - * @param deviceInfo with DeviceName UniqueId, Status, Disabled LastUpdate, PositionId, GroupId + * 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 updateDevice(TraccarDevice deviceInfo, int tenantId) throws TraccarConfigurationException, TrackerAlreadyExistException { - TrackerDeviceInfo res = null; + public void addDevice(TraccarDevice traccarDevice, int tenantId) throws + TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException { + TrackerDeviceInfo trackerDeviceInfo = null; try { TrackerManagementDAOFactory.openConnection(); - res = trackerDAO.getTrackerDevice(deviceInfo.getId(), tenantId); + trackerDeviceInfo = trackerDAO.getTrackerDevice(traccarDevice.getId(), tenantId); + if(trackerDeviceInfo!=null){ + String msg = "The device already exist"; + log.error(msg); + throw new TrackerAlreadyExistException(msg); + } } catch (TrackerManagementDAOException e) { String msg = "Error occurred while mapping with deviceId ."; log.error(msg, e); @@ -331,105 +330,92 @@ public class TraccarClientImpl implements TraccarClient { TrackerManagementDAOFactory.closeConnection(); } - if ((res==null) || (res.getTraccarDeviceId()==0)){ - try { - TraccarDevice device = deviceInfo; - String lastUpdatedTime = String.valueOf((new Date().getTime())); - device.setLastUpdate(lastUpdatedTime); - addDevice(deviceInfo, tenantId); - } catch (TraccarConfigurationException e) { - String msg = "Error occurred while mapping with groupId"; - log.error(msg, e); - throw new TraccarConfigurationException(msg, e); - } catch (TrackerAlreadyExistException e) { - String msg = "The group already exist"; - log.error(msg, e); - throw new TrackerAlreadyExistException(msg, e); - } - }else if (res!=null && (res.getTraccarDeviceId()!=0 && res.getStatus()==0)){ - //update the traccarGroupId and status - try { - TrackerManagementDAOFactory.beginTransaction(); - trackerDAO.updateTrackerDeviceIdANDStatus(res.getTraccarDeviceId(), deviceInfo.getId(), tenantId, 1); - TrackerManagementDAOFactory.commitTransaction(); - } catch (TransactionManagementException e) { - String msg = "Error occurred establishing the DB connection ."; - log.error(msg, e); - } catch (TrackerManagementDAOException e) { - String msg="Could not add the traccar group"; - log.error(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 res = executor.submit(new OkHttpClientThreadPool(url, payload, method)); + String result = res.get(); + if(result.charAt(0)=='{'){ + JSONObject obj = new JSONObject(result); + if (obj.has("id")){ + int traccarDeviceId = obj.getInt("id"); + int deviceId = traccarDevice.getId(); + 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 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(); + } + + JSONObject returnUser = new JSONObject(returnUser(username)); + setPermission(returnUser.getInt("id"),deviceId); + }else{ + log.error("Something went wrong_1: " + result); + } + }else{ + log.error("Something went wrong_2: " + result); } - }else{ - JSONObject payload = payload(deviceInfo); - String context = defaultPort+"/api/devices"; - Runnable trackerExecutor = new TrackerExecutor(deviceInfo.getId(), tenantId, endpoint, context, payload, - TraccarHandlerConstants.Methods.PUT, TraccarHandlerConstants.Types.DEVICE); - executor.execute(trackerExecutor); } - } - - private JSONObject payload(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 geoFenceIds = new ArrayList<>(); - payload.put("geofenceIds", geoFenceIds); - payload.put("attributes", new JSONObject()); - return payload; + //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 TraccarConfigurationException, TrackerAlreadyExistException { - TrackerDeviceInfo res = null; + public void updateLocation(TraccarDevice device, TraccarPosition deviceInfo, int tenantId) throws TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException { + TrackerDeviceInfo trackerDeviceInfo = null; try { TrackerManagementDAOFactory.openConnection(); - res = trackerDAO.getTrackerDevice(device.getId(), tenantId); + trackerDeviceInfo = trackerDAO.getTrackerDevice(device.getId(), tenantId); + log.info(trackerDeviceInfo); } catch (SQLException e) { String msg = "Error occurred establishing the DB connection ."; log.error(msg, e); + throw new TraccarConfigurationException(msg, e); } catch (TrackerManagementDAOException e) { - String msg="Could add new device location"; + String msg="Could not add new device location"; log.error(msg, e); + throw new TraccarConfigurationException(msg, e); } finally{ TrackerManagementDAOFactory.closeConnection(); } - if (res == null){ - try { - addDevice(device, tenantId); - } catch (TraccarConfigurationException e) { - String msg = "Error occurred add the new device"; - log.error(msg, e); - throw new TraccarConfigurationException(msg, e); - } catch (TrackerAlreadyExistException e) { - String msg = "The device already exist"; - log.error(msg, e); - throw new TrackerAlreadyExistException(msg, e); - } + //check if the device is already exist before updating the location + if (trackerDeviceInfo == null){ + //add device if not exist + log.info(trackerDeviceInfo); + addDevice(device, tenantId); }else{ - String context = locationUpdatePort+"/?id="+deviceInfo.getDeviceIdentifier()+"×tamp="+deviceInfo.getTimestamp()+ - "&lat="+deviceInfo.getLat()+"&lon="+deviceInfo.getLon()+"&bearing="+deviceInfo.getBearing()+ + //Update Location + String method = TraccarHandlerConstants.Methods.GET; + String url = locationUpdatePort+"/?id="+deviceInfo.getDeviceIdentifier()+ + "×tamp="+deviceInfo.getTimestamp()+"&lat="+deviceInfo.getLat()+ + "&lon="+deviceInfo.getLon()+"&bearing="+deviceInfo.getBearing()+ "&speed="+deviceInfo.getSpeed()+"&ignition=true"; - Runnable trackerExecutor = new TrackerExecutor(0, 0, endpoint, context, null, - TraccarHandlerConstants.Methods.GET, TraccarHandlerConstants.Types.DEVICE); - executor.execute(trackerExecutor); - log.info("Device GPS location added on traccar"); - } + executor.submit(new OkHttpClientThreadPool(url, null, method)); + //executor.shutdown(); + } } /** @@ -437,36 +423,54 @@ public class TraccarClientImpl implements TraccarClient { * @param deviceId identified via deviceIdentifier * @throws TraccarConfigurationException Failed while dis-enroll a Traccar Device operation */ - public void disEndrollDevice(int deviceId, int tenantId) throws TraccarConfigurationException { - TrackerDeviceInfo res = null; - JSONObject obj = null; + public void disEnrollDevice(int deviceId, int tenantId) throws TraccarConfigurationException { + TrackerDeviceInfo trackerDeviceInfo = null; + TrackerPermissionInfo trackerPermissionInfo = null; + JSONObject trackerDevice = null; + try { TrackerManagementDAOFactory.beginTransaction(); - res = trackerDAO.getTrackerDevice(deviceId, tenantId); - if(res!=null){ - obj = new JSONObject(res); - if(obj!=null){ - trackerDAO.removeTrackerDevice(deviceId, tenantId); - TrackerManagementDAOFactory.commitTransaction(); - } + trackerDeviceInfo = trackerDAO.getTrackerDevice(deviceId, tenantId); + trackerPermissionInfo = trackerDAO.getUserIdofPermissionByDeviceId(deviceId); + if(trackerDeviceInfo!=null){ + trackerDevice = new JSONObject(trackerDeviceInfo); + trackerDAO.removeTrackerDevice(deviceId, tenantId); + TrackerManagementDAOFactory.commitTransaction(); + } } 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(); } - if(obj != null){ - String context = defaultPort+"/api/devices/"+obj.getInt("traccarDeviceId"); - Runnable trackerExecutor = new TrackerExecutor(obj.getInt("traccarDeviceId"), tenantId, endpoint, context, null, - TraccarHandlerConstants.Methods.DELETE, TraccarHandlerConstants.Types.DEVICE); - executor.execute(trackerExecutor); + //Delete from traccar + if(trackerDevice!=null){ + String method = TraccarHandlerConstants.Methods.DELETE; + String url = defaultPort+"/api/devices/"+trackerDevice.getInt("traccarDeviceId"); + executor.submit(new OkHttpClientThreadPool(url, null, method)); + //executor.shutdown(); + //remove permissions + + log.info(new Gson().toJson(trackerPermissionInfo)); + log.info(trackerPermissionInfo); + if(trackerPermissionInfo!=null){ + try { + removePermission(trackerPermissionInfo.getTraccarUserId(),deviceId); + } catch (ExecutionException e) { + throw new RuntimeException(e); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } } } @@ -475,38 +479,71 @@ public class TraccarClientImpl implements TraccarClient { * @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 { - TrackerGroupInfo res = null; + public void addGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws + TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException { + TrackerGroupInfo trackerGroupInfo = null; try { TrackerManagementDAOFactory.openConnection(); - res = trackerDAO.getTrackerGroup(groupId, tenantId); - if (res!=null){ + 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 deviceId ."; + 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 ."; + String msg = "Error occurred establishing the DB connection."; log.error(msg, e); throw new TraccarConfigurationException(msg, e); } finally { TrackerManagementDAOFactory.closeConnection(); } - if (res==null){ - JSONObject payload = new JSONObject(); - payload.put("name", groupInfo.getName()); - payload.put("attributes", new JSONObject()); + 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 res = executor.submit(new OkHttpClientThreadPool(url, payload, method)); + String result = res.get(); - String context = defaultPort+"/api/groups"; - Runnable trackerExecutor = new TrackerExecutor(groupId, tenantId, endpoint, context, payload, - TraccarHandlerConstants.Methods.POST, TraccarHandlerConstants.Types.GROUP); - executor.execute(trackerExecutor); + 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(); } /** @@ -514,7 +551,8 @@ public class TraccarClientImpl implements TraccarClient { * @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 { + public void updateGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws + TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException { TrackerGroupInfo res = null; try { TrackerManagementDAOFactory.openConnection(); @@ -531,29 +569,23 @@ public class TraccarClientImpl implements TraccarClient { if ((res==null) || (res.getTraccarGroupId()==0)){ //add a new traccar group - try { - addGroup(groupInfo, groupId, tenantId); - } catch (TraccarConfigurationException e) { - String msg = "Error occurred while mapping with groupId"; - log.error(msg, e); - throw new TraccarConfigurationException(msg, e); - } catch (TrackerAlreadyExistException e) { - String msg = "The group already exist"; - log.error(msg, e); - throw new TrackerAlreadyExistException(msg, e); - } + 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); - } catch (TrackerManagementDAOException e) { - String msg="Could not add the traccar group"; - log.error(msg, e); + throw new TraccarConfigurationException(msg, e); } finally{ TrackerManagementDAOFactory.closeConnection(); } @@ -564,10 +596,11 @@ public class TraccarClientImpl implements TraccarClient { payload.put("name", groupInfo.getName()); payload.put("attributes", new JSONObject()); - String context = defaultPort+"/api/groups/"+obj.getInt("traccarGroupId"); - Runnable trackerExecutor = new TrackerExecutor(groupId, tenantId, endpoint, context, payload, - TraccarHandlerConstants.Methods.PUT, TraccarHandlerConstants.Types.GROUP); - executor.execute(trackerExecutor); + String method = TraccarHandlerConstants.Methods.PUT; + String url = defaultPort+"/api/groups/"+obj.getInt("traccarGroupId"); + + executor.submit(new OkHttpClientThreadPool(url, payload, method)); + //executor.shutdown(); } } @@ -576,7 +609,7 @@ public class TraccarClientImpl implements TraccarClient { * @param groupId * @throws TraccarConfigurationException Failed while add Traccar Device the operation */ - public void deleteGroup(int groupId, int tenantId) throws TraccarConfigurationException { + public void deleteGroup(int groupId, int tenantId) throws TraccarConfigurationException, ExecutionException, InterruptedException { TrackerGroupInfo res = null; JSONObject obj = null; try { @@ -587,6 +620,12 @@ public class TraccarClientImpl implements TraccarClient { 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)); + //executor.shutdown(); } } } catch (TransactionManagementException e) { @@ -600,66 +639,6 @@ public class TraccarClientImpl implements TraccarClient { } finally { TrackerManagementDAOFactory.closeConnection(); } - - if(obj!=null){ - String context = defaultPort+"/api/groups/"+obj.getInt("traccarGroupId"); - Runnable trackerExecutor = new TrackerExecutor(obj.getInt("traccarGroupId"), tenantId, endpoint, context, - null, TraccarHandlerConstants.Methods.DELETE, TraccarHandlerConstants.Types.GROUP); - executor.execute(trackerExecutor); - } - } - - public void fetchAllUsers(String type, TraccarUser traccarUser, int deviceId) throws TraccarConfigurationException { - String context = defaultPort+"/api/users/"; - - JSONObject payload = new JSONObject(); - payload.put("data", traccarUser); - - Runnable trackerExecutor = new TrackerExecutor(deviceId, 0, endpoint, context, - payload, TraccarHandlerConstants.Methods.GET, type); - executor.execute(trackerExecutor); - } - - private JSONObject TraccarUserPayload(TraccarUser traccarUser){ - JSONObject payload = new JSONObject(); - 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()); - return payload; - } - public void createUser(TraccarUser traccarUser, String type, int deviceId) throws TraccarConfigurationException { - JSONObject payload = TraccarUserPayload(traccarUser); - - String context = defaultPort+"/api/users"; - Runnable trackerExecutor = new TrackerExecutor(deviceId, 0, endpoint, context, payload, - TraccarHandlerConstants.Methods.POST, type); - executor.execute(trackerExecutor); - } - - public void updateUser(JSONObject traccarUser) throws TraccarConfigurationException { - /*JSONObject payload = traccarUser; - String context = defaultPort+"/api/users"; - Runnable trackerExecutor = new TrackerExecutor(0, 0, endpoint, context, payload, - TraccarHandlerConstants.Methods.PUT, TraccarHandlerConstants.Types.USER); - executor.execute(trackerExecutor);*/ - } - - public void setPermission(int userId, int deviceId) throws TraccarConfigurationException { - JSONObject payload = new JSONObject(); - payload.put("userId", userId); - payload.put("deviceId", deviceId); - - String context = defaultPort+"/api/permissions"; - Runnable trackerExecutor = new TrackerExecutor(deviceId, 0, endpoint, context, payload, - TraccarHandlerConstants.Methods.POST, TraccarHandlerConstants.Types.PERMISSION); - executor.execute(trackerExecutor); } public String generateRandomString(int len) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImplCopy.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImplCopy.java new file mode 100644 index 00000000000..b6dfd01b35e --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImplCopy.java @@ -0,0 +1,777 @@ +/* + * 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.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.json.JSONArray; +import org.json.JSONException; +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.exceptions.TrackerAlreadyExistException; +import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException; +import org.wso2.carbon.device.mgt.core.dao.TrackerDAO; +import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOException; +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.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 java.io.IOException; +import java.sql.SQLException; +import java.util.Date; +import java.util.Objects; +import java.util.Random; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +public class TraccarClientImplCopy /*implements TraccarClient*/ { + private static final Log log = LogFactory.getLog(TraccarClientImplCopy.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 TraccarClientImplCopy() { + client = new OkHttpClient.Builder() + .connectTimeout(30, TimeUnit.SECONDS) + .writeTimeout(30, TimeUnit.SECONDS) + .readTimeout(45, TimeUnit.SECONDS) + .connectionPool(new ConnectionPool(50,30,TimeUnit.SECONDS)) + .build(); + this.trackerDAO = TrackerManagementDAOFactory.getTrackerDAO(); + } + + private class TrackerExecutor implements Runnable { + final int deviceId; + final int groupId; + final int tenantId; + final JSONObject payload; + final String context; + final String publisherUrl; + private final String method; + private final String type; + + private TrackerExecutor(int id, int tenantId, String publisherUrl, String context, JSONObject payload, + String method, String type) { + this.deviceId = id; + this.groupId = id; + this.tenantId = tenantId; + this.payload = payload; + this.context = context; + this.publisherUrl = publisherUrl; + this.method = method; + this.type = type; + } + + public void run() { + 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)){ + builder = builder.delete(); + } + + request = builder.url(publisherUrl + context).addHeader(authorization, authorizationKey).build(); + String msg; + try { + response = client.newCall(request).execute(); + if(Objects.equals(method, TraccarHandlerConstants.Methods.POST)){ + String result = response.body().string(); + log.info(result); + if(Objects.equals(type, TraccarHandlerConstants.Types.PERMISSION)){ + if(result.equals("")){ + msg ="Successfully the device is assigned to the user"; + }else{ + msg = "Error occurred while fetching users ."; + } + log.info(msg); + }else if(result.charAt(0)=='{'){ + JSONObject obj = new JSONObject(result); + if (obj.has("id")){ + int traccarId = obj.getInt("id"); + try { + TrackerManagementDAOFactory.beginTransaction(); + if(Objects.equals(type, TraccarHandlerConstants.Types.DEVICE)){ + trackerDAO.addTrackerDevice(traccarId, deviceId, tenantId); + TrackerDeviceInfo res = trackerDAO.getTrackerDevice(deviceId, tenantId); + if(res.getStatus()==0){ + trackerDAO.updateTrackerDeviceIdANDStatus(res.getTraccarDeviceId(), deviceId, tenantId, 1); + + TraccarUser traccarUser = new TraccarUser(); + traccarUser.setName(username); + traccarUser.setLogin(username); + traccarUser.setEmail(username); + traccarUser.setPassword(generateRandomString(10)); + traccarUser.setToken(generateRandomString(32)); + traccarUser.setDeviceLimit(-1); + + log.info("=============="+new Gson().toJson(traccarUser)+"=============="); + //device is available + //device is not available + //user is available + //user is not available + fetchAllUsers(TraccarHandlerConstants.Types.USER_CREATE_WITH_INSERT_DEVICE, traccarUser, traccarId); + } + }else if(Objects.equals(type, TraccarHandlerConstants.Types.GROUP)){ + trackerDAO.addTrackerGroup(traccarId, groupId, tenantId); + TrackerGroupInfo res = trackerDAO.getTrackerGroup(groupId, tenantId); + if(res.getStatus()==0){ + trackerDAO.updateTrackerGroupIdANDStatus(res.getTraccarGroupId(), groupId, tenantId, 1); + } + }else if(Objects.equals(type, TraccarHandlerConstants.Types.USER_CREATE)){ + log.info("=============User inserted============="); + }else if(Objects.equals(type, TraccarHandlerConstants.Types.USER_CREATE_WITH_INSERT_DEVICE)){ + int userId = traccarId; + log.info("=============User inserted and setting to create session============="); + setPermission(userId, deviceId); + } + TrackerManagementDAOFactory.commitTransaction(); + } catch (JSONException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + msg = "Error occurred on JSON object ."; + log.error(msg, e); + } catch (TransactionManagementException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + msg = "Error occurred establishing the DB connection ."; + log.error(msg, e); + } catch (TrackerManagementDAOException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + msg = null; + switch (type) { + case TraccarHandlerConstants.Types.DEVICE: + msg = "Already device with deviceId " + deviceId + " exists"; + break; + case TraccarHandlerConstants.Types.GROUP: + msg = "Already the group with groupId - " + groupId + " exists!"; + break; + case TraccarHandlerConstants.Types.USER: + msg = "Error occurred while fetching users."; + break; + case TraccarHandlerConstants.Types.PERMISSION: + msg = "Error occurred while assigning the device to the user." + traccarId + deviceId; + break; + } + log.error(msg, e); + } finally { + TrackerManagementDAOFactory.closeConnection(); + } + } + response.close(); + } + if (log.isDebugEnabled()) { + log.debug("Successfully the request is proceed and communicated with Traccar"); + } + }else if(Objects.equals(method, TraccarHandlerConstants.Methods.GET)){ + if(!Objects.equals(type, TraccarHandlerConstants.Types.DEVICE)){ + response = client.newCall(request).execute(); + String result = response.body().string(); + + JSONArray fetchAllUsers = new JSONArray(result); + int userAvailability = 0; + int userId = 0; + for(int i=0; i geoFenceIds = new ArrayList<>(); + payload.put("geofenceIds", geoFenceIds); + payload.put("attributes", new JSONObject()); + return payload; + }*/ + + /** + * 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 TraccarConfigurationException, TrackerAlreadyExistException { + TrackerDeviceInfo res = null; + try { + TrackerManagementDAOFactory.openConnection(); + res = trackerDAO.getTrackerDevice(device.getId(), tenantId); + } catch (SQLException e) { + String msg = "Error occurred establishing the DB connection ."; + log.error(msg, e); + } catch (TrackerManagementDAOException e) { + String msg="Could add new device location"; + log.error(msg, e); + } finally{ + TrackerManagementDAOFactory.closeConnection(); + } + + if (res == null){ + try { + addDevice(device, tenantId); + } catch (TraccarConfigurationException e) { + String msg = "Error occurred add the new device"; + log.error(msg, e); + throw new TraccarConfigurationException(msg, e); + } catch (TrackerAlreadyExistException e) { + String msg = "The device already exist"; + log.error(msg, e); + throw new TrackerAlreadyExistException(msg, e); + } + }else{ + String context = locationUpdatePort+"/?id="+deviceInfo.getDeviceIdentifier()+"×tamp="+deviceInfo.getTimestamp()+ + "&lat="+deviceInfo.getLat()+"&lon="+deviceInfo.getLon()+"&bearing="+deviceInfo.getBearing()+ + "&speed="+deviceInfo.getSpeed()+"&ignition=true"; + Runnable trackerExecutor = new TrackerExecutor(0, 0, endpoint, context, null, + TraccarHandlerConstants.Methods.GET, TraccarHandlerConstants.Types.DEVICE); + executor.execute(trackerExecutor); + log.info("Device GPS location added on traccar"); + } + + } + + /** + * Dis-enroll a Device operation. + * @param deviceId identified via deviceIdentifier + * @throws TraccarConfigurationException Failed while dis-enroll a Traccar Device operation + */ + public void disEndrollDevice(int deviceId, int tenantId) throws TraccarConfigurationException { + TrackerDeviceInfo res = null; + JSONObject obj = null; + try { + TrackerManagementDAOFactory.beginTransaction(); + res = trackerDAO.getTrackerDevice(deviceId, tenantId); + if(res!=null){ + obj = new JSONObject(res); + if(obj!=null){ + trackerDAO.removeTrackerDevice(deviceId, tenantId); + TrackerManagementDAOFactory.commitTransaction(); + } + } + } 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 deviceId"; + log.error(msg, e); + } finally { + TrackerManagementDAOFactory.closeConnection(); + } + + if(obj != null){ + String context = defaultPort+"/api/devices/"+obj.getInt("traccarDeviceId"); + Runnable trackerExecutor = new TrackerExecutor(obj.getInt("traccarDeviceId"), tenantId, endpoint, context, null, + TraccarHandlerConstants.Methods.DELETE, TraccarHandlerConstants.Types.DEVICE); + executor.execute(trackerExecutor); + } + } + + /** + * 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 { + TrackerGroupInfo res = null; + try { + TrackerManagementDAOFactory.openConnection(); + res = trackerDAO.getTrackerGroup(groupId, tenantId); + if (res!=null){ + String msg = "The group already exit"; + log.error(msg); + throw new TrackerAlreadyExistException(msg); + } + } catch (TrackerManagementDAOException e) { + String msg = "Error occurred while mapping with deviceId ."; + 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(); + } + + + log.info("response.body().string()"); + try { + OkHttpClient client = new OkHttpClient().newBuilder() + .build(); + Request request = new Request.Builder() + .url("http://localhost/?token=b2zNFM9CvXAaHVxaQcLw22GgCXnaluy9") + .method("GET", null) + .build(); + Response response = client.newCall(request).execute(); + log.info(response.body().string()); + + /*Desktop desktop = java.awt.Desktop.getDesktop(); + URI oURL = new URI("http://localhost:8085"); + desktop.browse(oURL);*/ + } catch (IOException e) { + log.info("IOException e" +e); + } catch (Exception e) { + log.info("Exception e" +e ); + } + log.info("response.body().string()"); + + + if (res==null){ + JSONObject payload = new JSONObject(); + payload.put("name", groupInfo.getName()); + payload.put("attributes", new JSONObject()); + + String context = defaultPort+"/api/groups"; + Runnable trackerExecutor = new TrackerExecutor(groupId, tenantId, endpoint, context, payload, + TraccarHandlerConstants.Methods.POST, TraccarHandlerConstants.Types.GROUP); + executor.execute(trackerExecutor); + } + } + + /** + * 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 { + 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 + try { + addGroup(groupInfo, groupId, tenantId); + } catch (TraccarConfigurationException e) { + String msg = "Error occurred while mapping with groupId"; + log.error(msg, e); + throw new TraccarConfigurationException(msg, e); + } catch (TrackerAlreadyExistException e) { + String msg = "The group already exist"; + log.error(msg, e); + throw new TrackerAlreadyExistException(msg, e); + } + }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 (TransactionManagementException e) { + String msg = "Error occurred establishing the DB connection ."; + log.error(msg, e); + } catch (TrackerManagementDAOException e) { + String msg="Could not add the traccar group"; + log.error(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 context = defaultPort+"/api/groups/"+obj.getInt("traccarGroupId"); + Runnable trackerExecutor = new TrackerExecutor(groupId, tenantId, endpoint, context, payload, + TraccarHandlerConstants.Methods.PUT, TraccarHandlerConstants.Types.GROUP); + executor.execute(trackerExecutor); + } + } + + /** + * Add Traccar Device operation. + * @param groupId + * @throws TraccarConfigurationException Failed while add Traccar Device the operation + */ + public void deleteGroup(int groupId, int tenantId) throws TraccarConfigurationException { + 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(); + } + } + } 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(); + } + + if(obj!=null){ + String context = defaultPort+"/api/groups/"+obj.getInt("traccarGroupId"); + Runnable trackerExecutor = new TrackerExecutor(obj.getInt("traccarGroupId"), tenantId, endpoint, context, + null, TraccarHandlerConstants.Methods.DELETE, TraccarHandlerConstants.Types.GROUP); + executor.execute(trackerExecutor); + } + } + + public void fetchAllUsers(String type, TraccarUser traccarUser, int deviceId) throws TraccarConfigurationException { + String context = defaultPort+"/api/users/"; + + JSONObject payload = new JSONObject(); + payload.put("data", traccarUser); + + Runnable trackerExecutor = new TrackerExecutor(deviceId, 0, endpoint, context, + payload, TraccarHandlerConstants.Methods.GET, type); + executor.execute(trackerExecutor); + } + + /*private JSONObject TraccarUserPayload(TraccarUser traccarUser){ + JSONObject payload = new JSONObject(); + 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()); + + return payload; + }*/ + public void createUser(TraccarUser traccarUser, String type, int deviceId) throws TraccarConfigurationException { + JSONObject payload = TraccarUtil.TraccarUserPayload(traccarUser); + + String context = defaultPort+"/api/users"; + Runnable trackerExecutor = new TrackerExecutor(deviceId, 0, endpoint, context, payload, + TraccarHandlerConstants.Methods.POST, type); + executor.execute(trackerExecutor); + } + + public void updateUser(JSONObject traccarUser) throws TraccarConfigurationException { + /*JSONObject payload = traccarUser; + String context = defaultPort+"/api/users"; + Runnable trackerExecutor = new TrackerExecutor(0, 0, endpoint, context, payload, + TraccarHandlerConstants.Methods.PUT, TraccarHandlerConstants.Types.USER); + executor.execute(trackerExecutor);*/ + } + + public void setPermission(int userId, int deviceId) throws TraccarConfigurationException { + JSONObject payload = new JSONObject(); + payload.put("userId", userId); + payload.put("deviceId", deviceId); + + String context = defaultPort+"/api/permissions"; + Runnable trackerExecutor = new TrackerExecutor(deviceId, 0, endpoint, context, payload, + TraccarHandlerConstants.Methods.POST, TraccarHandlerConstants.Types.PERMISSION); + executor.execute(trackerExecutor); + } + + public String fetchAllUsers() { + OkHttpClient client = new OkHttpClient().newBuilder().build(); + Request request = new Request.Builder() + .url(endpoint+defaultPort+"/api/users") + .method("GET", null) + .addHeader(authorization, authorizationKey) + .build(); + try { + Response response = client.newCall(request).execute(); + return response.body().string(); + } catch (IOException e) { + return e.toString(); + } + } + + public String fetchUserInfo(String userName) throws TraccarConfigurationException { + String allUsers = fetchAllUsers(); //get all users + JSONArray fetchAllUsers = new JSONArray(allUsers); //loop users + for(int i=0; i geoFenceIds = new ArrayList<>(); + payload.put("geofenceIds", geoFenceIds); + payload.put("attributes", new JSONObject()); + return payload; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql index fb88cd39109..005db8fb7da 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql @@ -573,4 +573,32 @@ CREATE TABLE IF NOT EXISTS DM_BILLING ( PRIMARY KEY (INVOICE_ID), CONSTRAINT fk_DM_BILLING_DM_DEVICE2 FOREIGN KEY (DEVICE_ID) REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); \ No newline at end of file +); +-- 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-- diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql index 7e941e6be17..6fa6f7c4971 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql @@ -770,3 +770,10 @@ CREATE TABLE IF NOT EXISTS DM_EXT_DEVICE_MAPPING ( 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-- From 6ce4168d757e7e04b77e37ff4034848d868ad93a Mon Sep 17 00:00:00 2001 From: Rushdi Date: Sun, 15 May 2022 16:31:04 +0530 Subject: [PATCH 19/41] Update permissions --- .../device/mgt/core/dao/TrackerDAO.java | 5 +- .../core/dao/impl/tracker/TrackerDAOImpl.java | 9 +- .../api/service/addons/TraccarClientImpl.java | 24 +- .../service/addons/TraccarClientImplCopy.java | 777 ------------------ 4 files changed, 14 insertions(+), 801 deletions(-) delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImplCopy.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerDAO.java index 6deffa8846f..e7a0d635943 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerDAO.java @@ -97,15 +97,14 @@ public interface TrackerDAO { * @param deviceId mapping table. * @throws TrackerManagementDAOException */ - Boolean addTrackerUssrDevicePermission(int traccarUserId, int deviceId) throws TrackerManagementDAOException; + Boolean addTrackerUserDevicePermission(int traccarUserId, int deviceId) throws TrackerManagementDAOException; /** * Remove a permission on viewing a device. - * @param traccarUserId mapping table. * @param deviceId mapping table. * @throws TrackerManagementDAOException */ - Boolean removeTrackerUssrDevicePermission(int traccarUserId, int deviceId) throws TrackerManagementDAOException; + Boolean removeTrackerUserDevicePermission(int deviceId) throws TrackerManagementDAOException; TrackerPermissionInfo getUserIdofPermissionByDeviceId(int deviceId) throws TrackerManagementDAOException; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/tracker/TrackerDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/tracker/TrackerDAOImpl.java index aad9ba8b085..01b533a240e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/tracker/TrackerDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/tracker/TrackerDAOImpl.java @@ -216,7 +216,7 @@ public class TrackerDAOImpl implements TrackerDAO { } @Override - public Boolean addTrackerUssrDevicePermission(int traccarUserId, int deviceId) throws TrackerManagementDAOException { + public Boolean addTrackerUserDevicePermission(int traccarUserId, int deviceId) throws TrackerManagementDAOException { PreparedStatement stmt = null; try { Connection conn = TrackerManagementDAOFactory.getConnection(); @@ -235,14 +235,13 @@ public class TrackerDAOImpl implements TrackerDAO { } @Override - public Boolean removeTrackerUssrDevicePermission(int traccarUserId, int deviceId) throws TrackerManagementDAOException { + public Boolean removeTrackerUserDevicePermission(int deviceId) throws TrackerManagementDAOException { PreparedStatement stmt = null; try { Connection conn = TrackerManagementDAOFactory.getConnection(); - String sql = "DELETE FROM DM_EXT_PERMISSION_MAPPING WHERE TRACCAR_USER_ID=? AND TRACCAR_DEVICE_ID=?"; + String sql = "DELETE FROM DM_EXT_PERMISSION_MAPPING WHERE TRACCAR_DEVICE_ID=?"; stmt = conn.prepareStatement(sql); - stmt.setInt(1, traccarUserId); - stmt.setInt(2, deviceId); + stmt.setInt(1, deviceId); stmt.execute(); return true; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java index e24e855ae61..b88eca6f05a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java @@ -236,11 +236,10 @@ public class TraccarClientImpl implements TraccarClient { Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method)); String result = res.get(); //executor.shutdown(); - - if(result!=null){ + if(result==""){ try { TrackerManagementDAOFactory.beginTransaction(); - trackerDAO.addTrackerUssrDevicePermission(userId, deviceId); + trackerDAO.addTrackerUserDevicePermission(userId, deviceId); TrackerManagementDAOFactory.commitTransaction(); } catch (TrackerManagementDAOException e) { TrackerManagementDAOFactory.rollbackTransaction(); @@ -255,6 +254,8 @@ public class TraccarClientImpl implements TraccarClient { } finally { TrackerManagementDAOFactory.closeConnection(); } + }else{ + log.error("Couldnt add the permission record: "+ result); } } @@ -273,7 +274,7 @@ public class TraccarClientImpl implements TraccarClient { if(result!=null){ try { TrackerManagementDAOFactory.beginTransaction(); - trackerDAO.removeTrackerUssrDevicePermission(userId, deviceId); + trackerDAO.removeTrackerUserDevicePermission(deviceId); TrackerManagementDAOFactory.commitTransaction(); } catch (TrackerManagementDAOException e) { TrackerManagementDAOFactory.rollbackTransaction(); @@ -316,7 +317,7 @@ public class TraccarClientImpl implements TraccarClient { if(trackerDeviceInfo!=null){ String msg = "The device already exist"; log.error(msg); - throw new TrackerAlreadyExistException(msg); + //throw new TrackerAlreadyExistException(msg); } } catch (TrackerManagementDAOException e) { String msg = "Error occurred while mapping with deviceId ."; @@ -347,7 +348,6 @@ public class TraccarClientImpl implements TraccarClient { TrackerManagementDAOFactory.beginTransaction(); trackerDAO.addTrackerDevice(traccarDeviceId, deviceId, tenantId); trackerDeviceInfo = trackerDAO.getTrackerDevice(deviceId, tenantId); - if(trackerDeviceInfo.getStatus()==0){ trackerDAO.updateTrackerDeviceIdANDStatus(trackerDeviceInfo.getTraccarDeviceId(), deviceId, tenantId, 1); } @@ -366,13 +366,9 @@ public class TraccarClientImpl implements TraccarClient { TrackerManagementDAOFactory.closeConnection(); } - JSONObject returnUser = new JSONObject(returnUser(username)); - setPermission(returnUser.getInt("id"),deviceId); - }else{ - log.error("Something went wrong_1: " + result); + JSONObject returnUserInfo = new JSONObject(returnUser(username)); + setPermission(returnUserInfo.getInt("id"), traccarDeviceId); } - }else{ - log.error("Something went wrong_2: " + result); } } //executor.shutdown(); @@ -387,7 +383,6 @@ public class TraccarClientImpl implements TraccarClient { try { TrackerManagementDAOFactory.openConnection(); trackerDeviceInfo = trackerDAO.getTrackerDevice(device.getId(), tenantId); - log.info(trackerDeviceInfo); } catch (SQLException e) { String msg = "Error occurred establishing the DB connection ."; log.error(msg, e); @@ -403,7 +398,6 @@ public class TraccarClientImpl implements TraccarClient { //check if the device is already exist before updating the location if (trackerDeviceInfo == null){ //add device if not exist - log.info(trackerDeviceInfo); addDevice(device, tenantId); }else{ //Update Location @@ -460,8 +454,6 @@ public class TraccarClientImpl implements TraccarClient { //executor.shutdown(); //remove permissions - log.info(new Gson().toJson(trackerPermissionInfo)); - log.info(trackerPermissionInfo); if(trackerPermissionInfo!=null){ try { removePermission(trackerPermissionInfo.getTraccarUserId(),deviceId); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImplCopy.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImplCopy.java deleted file mode 100644 index b6dfd01b35e..00000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImplCopy.java +++ /dev/null @@ -1,777 +0,0 @@ -/* - * 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.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.json.JSONArray; -import org.json.JSONException; -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.exceptions.TrackerAlreadyExistException; -import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException; -import org.wso2.carbon.device.mgt.core.dao.TrackerDAO; -import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOException; -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.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 java.io.IOException; -import java.sql.SQLException; -import java.util.Date; -import java.util.Objects; -import java.util.Random; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -public class TraccarClientImplCopy /*implements TraccarClient*/ { - private static final Log log = LogFactory.getLog(TraccarClientImplCopy.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 TraccarClientImplCopy() { - client = new OkHttpClient.Builder() - .connectTimeout(30, TimeUnit.SECONDS) - .writeTimeout(30, TimeUnit.SECONDS) - .readTimeout(45, TimeUnit.SECONDS) - .connectionPool(new ConnectionPool(50,30,TimeUnit.SECONDS)) - .build(); - this.trackerDAO = TrackerManagementDAOFactory.getTrackerDAO(); - } - - private class TrackerExecutor implements Runnable { - final int deviceId; - final int groupId; - final int tenantId; - final JSONObject payload; - final String context; - final String publisherUrl; - private final String method; - private final String type; - - private TrackerExecutor(int id, int tenantId, String publisherUrl, String context, JSONObject payload, - String method, String type) { - this.deviceId = id; - this.groupId = id; - this.tenantId = tenantId; - this.payload = payload; - this.context = context; - this.publisherUrl = publisherUrl; - this.method = method; - this.type = type; - } - - public void run() { - 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)){ - builder = builder.delete(); - } - - request = builder.url(publisherUrl + context).addHeader(authorization, authorizationKey).build(); - String msg; - try { - response = client.newCall(request).execute(); - if(Objects.equals(method, TraccarHandlerConstants.Methods.POST)){ - String result = response.body().string(); - log.info(result); - if(Objects.equals(type, TraccarHandlerConstants.Types.PERMISSION)){ - if(result.equals("")){ - msg ="Successfully the device is assigned to the user"; - }else{ - msg = "Error occurred while fetching users ."; - } - log.info(msg); - }else if(result.charAt(0)=='{'){ - JSONObject obj = new JSONObject(result); - if (obj.has("id")){ - int traccarId = obj.getInt("id"); - try { - TrackerManagementDAOFactory.beginTransaction(); - if(Objects.equals(type, TraccarHandlerConstants.Types.DEVICE)){ - trackerDAO.addTrackerDevice(traccarId, deviceId, tenantId); - TrackerDeviceInfo res = trackerDAO.getTrackerDevice(deviceId, tenantId); - if(res.getStatus()==0){ - trackerDAO.updateTrackerDeviceIdANDStatus(res.getTraccarDeviceId(), deviceId, tenantId, 1); - - TraccarUser traccarUser = new TraccarUser(); - traccarUser.setName(username); - traccarUser.setLogin(username); - traccarUser.setEmail(username); - traccarUser.setPassword(generateRandomString(10)); - traccarUser.setToken(generateRandomString(32)); - traccarUser.setDeviceLimit(-1); - - log.info("=============="+new Gson().toJson(traccarUser)+"=============="); - //device is available - //device is not available - //user is available - //user is not available - fetchAllUsers(TraccarHandlerConstants.Types.USER_CREATE_WITH_INSERT_DEVICE, traccarUser, traccarId); - } - }else if(Objects.equals(type, TraccarHandlerConstants.Types.GROUP)){ - trackerDAO.addTrackerGroup(traccarId, groupId, tenantId); - TrackerGroupInfo res = trackerDAO.getTrackerGroup(groupId, tenantId); - if(res.getStatus()==0){ - trackerDAO.updateTrackerGroupIdANDStatus(res.getTraccarGroupId(), groupId, tenantId, 1); - } - }else if(Objects.equals(type, TraccarHandlerConstants.Types.USER_CREATE)){ - log.info("=============User inserted============="); - }else if(Objects.equals(type, TraccarHandlerConstants.Types.USER_CREATE_WITH_INSERT_DEVICE)){ - int userId = traccarId; - log.info("=============User inserted and setting to create session============="); - setPermission(userId, deviceId); - } - TrackerManagementDAOFactory.commitTransaction(); - } catch (JSONException e) { - TrackerManagementDAOFactory.rollbackTransaction(); - msg = "Error occurred on JSON object ."; - log.error(msg, e); - } catch (TransactionManagementException e) { - TrackerManagementDAOFactory.rollbackTransaction(); - msg = "Error occurred establishing the DB connection ."; - log.error(msg, e); - } catch (TrackerManagementDAOException e) { - TrackerManagementDAOFactory.rollbackTransaction(); - msg = null; - switch (type) { - case TraccarHandlerConstants.Types.DEVICE: - msg = "Already device with deviceId " + deviceId + " exists"; - break; - case TraccarHandlerConstants.Types.GROUP: - msg = "Already the group with groupId - " + groupId + " exists!"; - break; - case TraccarHandlerConstants.Types.USER: - msg = "Error occurred while fetching users."; - break; - case TraccarHandlerConstants.Types.PERMISSION: - msg = "Error occurred while assigning the device to the user." + traccarId + deviceId; - break; - } - log.error(msg, e); - } finally { - TrackerManagementDAOFactory.closeConnection(); - } - } - response.close(); - } - if (log.isDebugEnabled()) { - log.debug("Successfully the request is proceed and communicated with Traccar"); - } - }else if(Objects.equals(method, TraccarHandlerConstants.Methods.GET)){ - if(!Objects.equals(type, TraccarHandlerConstants.Types.DEVICE)){ - response = client.newCall(request).execute(); - String result = response.body().string(); - - JSONArray fetchAllUsers = new JSONArray(result); - int userAvailability = 0; - int userId = 0; - for(int i=0; i geoFenceIds = new ArrayList<>(); - payload.put("geofenceIds", geoFenceIds); - payload.put("attributes", new JSONObject()); - return payload; - }*/ - - /** - * 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 TraccarConfigurationException, TrackerAlreadyExistException { - TrackerDeviceInfo res = null; - try { - TrackerManagementDAOFactory.openConnection(); - res = trackerDAO.getTrackerDevice(device.getId(), tenantId); - } catch (SQLException e) { - String msg = "Error occurred establishing the DB connection ."; - log.error(msg, e); - } catch (TrackerManagementDAOException e) { - String msg="Could add new device location"; - log.error(msg, e); - } finally{ - TrackerManagementDAOFactory.closeConnection(); - } - - if (res == null){ - try { - addDevice(device, tenantId); - } catch (TraccarConfigurationException e) { - String msg = "Error occurred add the new device"; - log.error(msg, e); - throw new TraccarConfigurationException(msg, e); - } catch (TrackerAlreadyExistException e) { - String msg = "The device already exist"; - log.error(msg, e); - throw new TrackerAlreadyExistException(msg, e); - } - }else{ - String context = locationUpdatePort+"/?id="+deviceInfo.getDeviceIdentifier()+"×tamp="+deviceInfo.getTimestamp()+ - "&lat="+deviceInfo.getLat()+"&lon="+deviceInfo.getLon()+"&bearing="+deviceInfo.getBearing()+ - "&speed="+deviceInfo.getSpeed()+"&ignition=true"; - Runnable trackerExecutor = new TrackerExecutor(0, 0, endpoint, context, null, - TraccarHandlerConstants.Methods.GET, TraccarHandlerConstants.Types.DEVICE); - executor.execute(trackerExecutor); - log.info("Device GPS location added on traccar"); - } - - } - - /** - * Dis-enroll a Device operation. - * @param deviceId identified via deviceIdentifier - * @throws TraccarConfigurationException Failed while dis-enroll a Traccar Device operation - */ - public void disEndrollDevice(int deviceId, int tenantId) throws TraccarConfigurationException { - TrackerDeviceInfo res = null; - JSONObject obj = null; - try { - TrackerManagementDAOFactory.beginTransaction(); - res = trackerDAO.getTrackerDevice(deviceId, tenantId); - if(res!=null){ - obj = new JSONObject(res); - if(obj!=null){ - trackerDAO.removeTrackerDevice(deviceId, tenantId); - TrackerManagementDAOFactory.commitTransaction(); - } - } - } 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 deviceId"; - log.error(msg, e); - } finally { - TrackerManagementDAOFactory.closeConnection(); - } - - if(obj != null){ - String context = defaultPort+"/api/devices/"+obj.getInt("traccarDeviceId"); - Runnable trackerExecutor = new TrackerExecutor(obj.getInt("traccarDeviceId"), tenantId, endpoint, context, null, - TraccarHandlerConstants.Methods.DELETE, TraccarHandlerConstants.Types.DEVICE); - executor.execute(trackerExecutor); - } - } - - /** - * 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 { - TrackerGroupInfo res = null; - try { - TrackerManagementDAOFactory.openConnection(); - res = trackerDAO.getTrackerGroup(groupId, tenantId); - if (res!=null){ - String msg = "The group already exit"; - log.error(msg); - throw new TrackerAlreadyExistException(msg); - } - } catch (TrackerManagementDAOException e) { - String msg = "Error occurred while mapping with deviceId ."; - 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(); - } - - - log.info("response.body().string()"); - try { - OkHttpClient client = new OkHttpClient().newBuilder() - .build(); - Request request = new Request.Builder() - .url("http://localhost/?token=b2zNFM9CvXAaHVxaQcLw22GgCXnaluy9") - .method("GET", null) - .build(); - Response response = client.newCall(request).execute(); - log.info(response.body().string()); - - /*Desktop desktop = java.awt.Desktop.getDesktop(); - URI oURL = new URI("http://localhost:8085"); - desktop.browse(oURL);*/ - } catch (IOException e) { - log.info("IOException e" +e); - } catch (Exception e) { - log.info("Exception e" +e ); - } - log.info("response.body().string()"); - - - if (res==null){ - JSONObject payload = new JSONObject(); - payload.put("name", groupInfo.getName()); - payload.put("attributes", new JSONObject()); - - String context = defaultPort+"/api/groups"; - Runnable trackerExecutor = new TrackerExecutor(groupId, tenantId, endpoint, context, payload, - TraccarHandlerConstants.Methods.POST, TraccarHandlerConstants.Types.GROUP); - executor.execute(trackerExecutor); - } - } - - /** - * 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 { - 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 - try { - addGroup(groupInfo, groupId, tenantId); - } catch (TraccarConfigurationException e) { - String msg = "Error occurred while mapping with groupId"; - log.error(msg, e); - throw new TraccarConfigurationException(msg, e); - } catch (TrackerAlreadyExistException e) { - String msg = "The group already exist"; - log.error(msg, e); - throw new TrackerAlreadyExistException(msg, e); - } - }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 (TransactionManagementException e) { - String msg = "Error occurred establishing the DB connection ."; - log.error(msg, e); - } catch (TrackerManagementDAOException e) { - String msg="Could not add the traccar group"; - log.error(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 context = defaultPort+"/api/groups/"+obj.getInt("traccarGroupId"); - Runnable trackerExecutor = new TrackerExecutor(groupId, tenantId, endpoint, context, payload, - TraccarHandlerConstants.Methods.PUT, TraccarHandlerConstants.Types.GROUP); - executor.execute(trackerExecutor); - } - } - - /** - * Add Traccar Device operation. - * @param groupId - * @throws TraccarConfigurationException Failed while add Traccar Device the operation - */ - public void deleteGroup(int groupId, int tenantId) throws TraccarConfigurationException { - 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(); - } - } - } 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(); - } - - if(obj!=null){ - String context = defaultPort+"/api/groups/"+obj.getInt("traccarGroupId"); - Runnable trackerExecutor = new TrackerExecutor(obj.getInt("traccarGroupId"), tenantId, endpoint, context, - null, TraccarHandlerConstants.Methods.DELETE, TraccarHandlerConstants.Types.GROUP); - executor.execute(trackerExecutor); - } - } - - public void fetchAllUsers(String type, TraccarUser traccarUser, int deviceId) throws TraccarConfigurationException { - String context = defaultPort+"/api/users/"; - - JSONObject payload = new JSONObject(); - payload.put("data", traccarUser); - - Runnable trackerExecutor = new TrackerExecutor(deviceId, 0, endpoint, context, - payload, TraccarHandlerConstants.Methods.GET, type); - executor.execute(trackerExecutor); - } - - /*private JSONObject TraccarUserPayload(TraccarUser traccarUser){ - JSONObject payload = new JSONObject(); - 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()); - - return payload; - }*/ - public void createUser(TraccarUser traccarUser, String type, int deviceId) throws TraccarConfigurationException { - JSONObject payload = TraccarUtil.TraccarUserPayload(traccarUser); - - String context = defaultPort+"/api/users"; - Runnable trackerExecutor = new TrackerExecutor(deviceId, 0, endpoint, context, payload, - TraccarHandlerConstants.Methods.POST, type); - executor.execute(trackerExecutor); - } - - public void updateUser(JSONObject traccarUser) throws TraccarConfigurationException { - /*JSONObject payload = traccarUser; - String context = defaultPort+"/api/users"; - Runnable trackerExecutor = new TrackerExecutor(0, 0, endpoint, context, payload, - TraccarHandlerConstants.Methods.PUT, TraccarHandlerConstants.Types.USER); - executor.execute(trackerExecutor);*/ - } - - public void setPermission(int userId, int deviceId) throws TraccarConfigurationException { - JSONObject payload = new JSONObject(); - payload.put("userId", userId); - payload.put("deviceId", deviceId); - - String context = defaultPort+"/api/permissions"; - Runnable trackerExecutor = new TrackerExecutor(deviceId, 0, endpoint, context, payload, - TraccarHandlerConstants.Methods.POST, TraccarHandlerConstants.Types.PERMISSION); - executor.execute(trackerExecutor); - } - - public String fetchAllUsers() { - OkHttpClient client = new OkHttpClient().newBuilder().build(); - Request request = new Request.Builder() - .url(endpoint+defaultPort+"/api/users") - .method("GET", null) - .addHeader(authorization, authorizationKey) - .build(); - try { - Response response = client.newCall(request).execute(); - return response.body().string(); - } catch (IOException e) { - return e.toString(); - } - } - - public String fetchUserInfo(String userName) throws TraccarConfigurationException { - String allUsers = fetchAllUsers(); //get all users - JSONArray fetchAllUsers = new JSONArray(allUsers); //loop users - for(int i=0; i Date: Sun, 15 May 2022 19:42:23 +0530 Subject: [PATCH 20/41] Update remove permission --- .../api/service/addons/TraccarClientImpl.java | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java index b88eca6f05a..1beba4a859a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java @@ -425,12 +425,15 @@ public class TraccarClientImpl implements TraccarClient { try { TrackerManagementDAOFactory.beginTransaction(); trackerDeviceInfo = trackerDAO.getTrackerDevice(deviceId, tenantId); - trackerPermissionInfo = trackerDAO.getUserIdofPermissionByDeviceId(deviceId); if(trackerDeviceInfo!=null){ trackerDevice = new JSONObject(trackerDeviceInfo); trackerDAO.removeTrackerDevice(deviceId, tenantId); TrackerManagementDAOFactory.commitTransaction(); + log.error(trackerDevice.getInt("traccarDeviceId")); + trackerPermissionInfo = trackerDAO.getUserIdofPermissionByDeviceId(trackerDevice.getInt("traccarDeviceId")); + log.error(trackerPermissionInfo); + log.error(new Gson().toJson(trackerPermissionInfo)); } } catch (TransactionManagementException e) { TrackerManagementDAOFactory.rollbackTransaction(); @@ -456,11 +459,13 @@ public class TraccarClientImpl implements TraccarClient { if(trackerPermissionInfo!=null){ try { - removePermission(trackerPermissionInfo.getTraccarUserId(),deviceId); + removePermission(trackerPermissionInfo.getTraccarUserId(),trackerDevice.getInt("traccarDeviceId")); } catch (ExecutionException e) { - throw new RuntimeException(e); + log.error("ExecutionException : " + e); + //throw new RuntimeException(e); } catch (InterruptedException e) { - throw new RuntimeException(e); + log.error("InterruptedException : " + e); + //throw new RuntimeException(e); } } } From 11fa624b39dbd4a99b9f362dc63fa43e525a6f2c Mon Sep 17 00:00:00 2001 From: Rushdi Date: Sun, 15 May 2022 21:29:09 +0530 Subject: [PATCH 21/41] Add tracker API endpoint to return user token --- .../service/api/DeviceManagementService.java | 60 ++++++++ .../mgt/jaxrs/service/api/TraccarService.java | 141 ------------------ .../impl/DeviceManagementServiceImpl.java | 24 +++ .../service/impl/TraccarServiceImpl.java | 59 -------- .../src/main/webapp/WEB-INF/cxf-servlet.xml | 2 - 5 files changed, 84 insertions(+), 202 deletions(-) delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/TraccarService.java delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/TraccarServiceImpl.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java index e2d88ea046a..02efa62f237 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java @@ -583,6 +583,66 @@ public interface DeviceManagementService { @QueryParam("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( + @ApiParam( + name = "name", + value = "Boolean flag indicating whether to include device-info (location, application list etc) \n" + + " to the device object.", + required = false) + @QueryParam("name") + String name); + @GET @Produces(MediaType.APPLICATION_JSON) @Path("/{groupId}/location-history") diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/TraccarService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/TraccarService.java deleted file mode 100644 index 33af90ce105..00000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/TraccarService.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * 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. - * - */ - -package org.wso2.carbon.device.mgt.jaxrs.service.api; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Extension; -import io.swagger.annotations.ExtensionProperty; -import io.swagger.annotations.Info; -import io.swagger.annotations.ResponseHeader; -import io.swagger.annotations.SwaggerDefinition; -import io.swagger.annotations.Tag; -import org.wso2.carbon.apimgt.annotations.api.Scope; -import org.wso2.carbon.apimgt.annotations.api.Scopes; -import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; -import org.wso2.carbon.device.mgt.jaxrs.beans.OperationList; -import org.wso2.carbon.device.mgt.jaxrs.common.ActivityIdList; -import org.wso2.carbon.device.mgt.jaxrs.util.Constants; - -import javax.validation.constraints.Size; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -/** - * traccar related REST-API. This can be used to manipulated traccar related details. - */ -@SwaggerDefinition( - info = @Info( - version = "1.0.0", - title = "", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = "name", value = "TraccarService"), - @ExtensionProperty(name = "context", value = "/api/device-mgt/v1.0/traccar"), - }) - } - ), - tags = { - @Tag(name = "traccar_service", description = "") - } -) -@Scopes( - scopes = { - @Scope( - name = "Return Traccar User token ", - description = "Enroll a Traccar User if not exist and return the token", - key = "perm:traccar:user", - roles = {"Internal/devicemgt-user"}, - permissions = {"/device-mgt/traccar/manage"} - ) - } -) - -@Path("/traccar") -@Produces(MediaType.APPLICATION_JSON) -@Api(value = "Traccar Service", description = "Traccar Service") -public interface TraccarService { - - @GET - @Produces(MediaType.APPLICATION_JSON) - @Path("/generate-token") - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - httpMethod = "GET", - value = "Return Traccar User Token", - tags = "Traccar Service", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:traccar:user") - }) - } - ) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "OK. \n Successfully retrieved the operations.", - response = OperationList.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 has been modified the last " + - "time.\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) - }) - Response getUser( - @ApiParam( - name = "userName", - value = "The user name.", - required = true) - @QueryParam("userName") String userName); -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java index 6e6882cfb85..bebef1bcf02 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -42,6 +42,7 @@ import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.json.JSONObject; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.application.mgt.common.ApplicationInstallResponse; @@ -97,7 +98,9 @@ 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.service.DeviceManagementProviderService; 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.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.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceCompliance; @@ -463,6 +466,27 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { } } + @GET + @Override + @Path("/traccar-user-token") + public Response getTraccarUserToken(@QueryParam("name") String name) { + + if (HttpReportingUtil.isTrackerEnabled()) { + JSONObject obj = new JSONObject(DeviceAPIClientServiceImpl.returnUser(name)); + + log.info("================="); + log.info(obj.toString()); + log.info("=================="); + if(obj.has("error")){ + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(obj.getString("error")).build(); + }else{ + 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. * diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/TraccarServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/TraccarServiceImpl.java deleted file mode 100644 index 718d2a47fc9..00000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/TraccarServiceImpl.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * 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. - * - */ -package org.wso2.carbon.device.mgt.jaxrs.service.impl; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.json.JSONObject; -import org.wso2.carbon.device.mgt.core.traccar.api.service.impl.DeviceAPIClientServiceImpl; -import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil; -import org.wso2.carbon.device.mgt.jaxrs.service.api.TraccarService; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -@Path("/traccar") -@Produces(MediaType.APPLICATION_JSON) -public class TraccarServiceImpl implements TraccarService { - private static final Log log = LogFactory.getLog(TraccarServiceImpl.class); - - @GET - @Path("/generate-token") - @Override - public Response getUser(@QueryParam("userName") String userName) { - if (HttpReportingUtil.isTrackerEnabled()) { - JSONObject obj = new JSONObject(DeviceAPIClientServiceImpl.returnUser(userName)); - - log.info("================="); - log.info(obj.toString()); - log.info("=================="); - if(obj.has("error")){ - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(obj.getString("error")).build(); - }else{ - 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(); - } - } -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml index e80349a4b7b..efce569c420 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -49,7 +49,6 @@ - @@ -100,7 +99,6 @@ - From 6b3294bd6013fa855213bc6c88afed9c02a55227 Mon Sep 17 00:00:00 2001 From: Rushdi Date: Tue, 17 May 2022 21:42:06 +0530 Subject: [PATCH 22/41] Update tracker get token api --- .../mgt/jaxrs/service/api/DeviceManagementService.java | 9 +-------- .../jaxrs/service/impl/DeviceManagementServiceImpl.java | 6 ++++-- 2 files changed, 5 insertions(+), 10 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java index 02efa62f237..8ea4cd2f323 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java @@ -634,14 +634,7 @@ public interface DeviceManagementService { response = ErrorResponse.class) }) @Path("/traccar-user-token") - Response getTraccarUserToken( - @ApiParam( - name = "name", - value = "Boolean flag indicating whether to include device-info (location, application list etc) \n" + - " to the device object.", - required = false) - @QueryParam("name") - String name); + Response getTraccarUserToken(); @GET @Produces(MediaType.APPLICATION_JSON) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java index bebef1bcf02..c57f0463da6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -469,12 +469,14 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @GET @Override @Path("/traccar-user-token") - public Response getTraccarUserToken(@QueryParam("name") String name) { + public Response getTraccarUserToken() { if (HttpReportingUtil.isTrackerEnabled()) { - JSONObject obj = new JSONObject(DeviceAPIClientServiceImpl.returnUser(name)); + String loggedUserName = CarbonContext.getThreadLocalCarbonContext().getUsername(); + JSONObject obj = new JSONObject(DeviceAPIClientServiceImpl.returnUser(loggedUserName)); log.info("================="); + log.info(loggedUserName); log.info(obj.toString()); log.info("=================="); if(obj.has("error")){ From a521985e98857bf02b2dd1f64e49147e453b4005 Mon Sep 17 00:00:00 2001 From: Rushdi Date: Tue, 17 May 2022 21:53:00 +0530 Subject: [PATCH 23/41] Update tracker get token api --- .../mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java index c57f0463da6..572cdcf8845 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -472,11 +472,10 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { public Response getTraccarUserToken() { if (HttpReportingUtil.isTrackerEnabled()) { - String loggedUserName = CarbonContext.getThreadLocalCarbonContext().getUsername(); - JSONObject obj = new JSONObject(DeviceAPIClientServiceImpl.returnUser(loggedUserName)); + String currentUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); + JSONObject obj = new JSONObject(DeviceAPIClientServiceImpl.returnUser(currentUser)); log.info("================="); - log.info(loggedUserName); log.info(obj.toString()); log.info("=================="); if(obj.has("error")){ From 35a5230ef73f27fb71f28de813faf2337e3cf2a5 Mon Sep 17 00:00:00 2001 From: Rushdi Date: Tue, 17 May 2022 22:45:40 +0530 Subject: [PATCH 24/41] Fix admin login to tracker --- .../mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java | 1 + .../core/traccar/api/service/addons/TraccarClientImpl.java | 4 +++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java index 572cdcf8845..9d9448653a1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -476,6 +476,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { JSONObject obj = new JSONObject(DeviceAPIClientServiceImpl.returnUser(currentUser)); log.info("================="); + log.info(currentUser); log.info(obj.toString()); log.info("=================="); if(obj.has("error")){ diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java index 1beba4a859a..7b3458bbcf3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java @@ -176,7 +176,9 @@ public class TraccarClientImpl implements TraccarClient { traccarUser.setId(obj.getInt("id")); traccarUser.setName(obj.getString("name")); - traccarUser.setLogin(obj.getString("login")); + if(!obj.isNull("login")){ + traccarUser.setLogin(obj.getString("login")); + } traccarUser.setEmail(obj.getString("email")); traccarUser.setDeviceLimit(obj.getInt("deviceLimit")); traccarUser.setUserLimit(obj.getInt("userLimit")); From 83651efcb50d4e84f14aca3748d571db794d1f26 Mon Sep 17 00:00:00 2001 From: Rushdi Date: Wed, 18 May 2022 18:01:38 +0530 Subject: [PATCH 25/41] Remove unwanted codes --- .../mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java | 1 - 1 file changed, 1 deletion(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java index 9d9448653a1..572cdcf8845 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -476,7 +476,6 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { JSONObject obj = new JSONObject(DeviceAPIClientServiceImpl.returnUser(currentUser)); log.info("================="); - log.info(currentUser); log.info(obj.toString()); log.info("=================="); if(obj.has("error")){ From f4d0050270bb1f9b1545e8d8e0d38465c9738440 Mon Sep 17 00:00:00 2001 From: Rushdi Date: Fri, 27 May 2022 01:15:53 +0530 Subject: [PATCH 26/41] fix removing permission and organizing the code --- .../impl/DeviceManagementServiceImpl.java | 102 ++++++++++- .../wso2/carbon/device/mgt/common/Device.java | 4 + .../device/mgt/common/TrackerDeviceInfo.java | 8 +- .../device/mgt/common/TrackerGroupInfo.java | 8 +- .../mgt/common/TrackerPermissionInfo.java | 8 +- .../device/mgt/common/TrackerUserInfo.java | 8 +- .../TrackerAlreadyExistException.java | 24 +-- .../carbon/device/mgt/core/dao/DeviceDAO.java | 34 ++-- .../device/mgt/core/dao/TrackerDAO.java | 60 +++++-- .../dao/TrackerManagementDAOException.java | 24 +-- .../core/dao/TrackerManagementDAOFactory.java | 24 +-- .../dao/impl/device/GenericDeviceDAOImpl.java | 78 ++++++++- .../dao/impl/device/OracleDeviceDAOImpl.java | 77 ++++++++- .../impl/device/PostgreSQLDeviceDAOImpl.java | 77 ++++++++- .../impl/device/SQLServerDeviceDAOImpl.java | 75 +++++++++ .../core/dao/impl/tracker/TrackerDAOImpl.java | 153 +++++++++++------ .../dao/util/DeviceManagementDAOUtil.java | 16 ++ .../dao/util/TrackerManagementDAOUtil.java | 73 ++++++-- .../impl/DeviceInformationManagerImpl.java | 2 + .../DeviceManagementProviderService.java | 21 ++- .../DeviceManagementProviderServiceImpl.java | 49 +++++- .../traccar/api/service/TraccarClient.java | 24 ++- .../api/service/addons/TraccarClientImpl.java | 158 +++++++++++++----- .../impl/DeviceAPIClientServiceImpl.java | 45 ++++- .../common/TraccarHandlerConstants.java | 10 +- .../traccar/common/beans/TraccarUser.java | 1 + .../config/TraccarConfigurationException.java | 13 +- .../core/traccar/common/util/TraccarUtil.java | 19 +++ 28 files changed, 967 insertions(+), 228 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java index 572cdcf8845..9fea7b108c6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -42,6 +42,7 @@ import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; 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.PrivilegedCarbonContext; @@ -61,6 +62,8 @@ import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.PaginationRequest; 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.ApplicationManagementException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; @@ -88,6 +91,7 @@ import org.wso2.carbon.device.mgt.common.search.PropertyMap; import org.wso2.carbon.device.mgt.common.search.SearchContext; import org.wso2.carbon.device.mgt.common.type.mgt.DeviceStatus; 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.DeviceInformationManager; import org.wso2.carbon.device.mgt.core.dto.DeviceType; @@ -99,6 +103,7 @@ import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.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.HttpReportingUtil; import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList; @@ -133,6 +138,11 @@ import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; 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") public class DeviceManagementServiceImpl implements DeviceManagementService { @@ -475,12 +485,98 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { String currentUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); JSONObject obj = new JSONObject(DeviceAPIClientServiceImpl.returnUser(currentUser)); - log.info("================="); - log.info(obj.toString()); - log.info("=================="); if(obj.has("error")){ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(obj.getString("error")).build(); }else{ + int userId = obj.getInt("id"); + List 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 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()); + devices.setCount(0); + }else{ + devices.setList((List) result.getData()); + devices.setCount(result.getRecordsTotal()); + } + + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + for(int i=0; i getAllUserDevices = + DeviceAPIClientServiceImpl.getUserIdofPermissionByUserIdNIdList(userId, traccarValidIdList); + for (TrackerPermissionInfo getAllUserDevice : getAllUserDevices) { + DeviceAPIClientServiceImpl.removeTrackerUserDevicePermission( + getAllUserDevice.getTraccarUserId(), + getAllUserDevice.getTraccarDeviceId(), + TraccarHandlerConstants.Types.REMOVE_TYPE_SINGLE); + } + + } catch (JSONException e){ + String msg = "not a JSONObject, "; + log.error(msg); + } catch (DeviceManagementException e) { + String msg = "Error occurred while fetching all enrolled devices"; + log.error(msg, e); + } catch (DeviceAccessAuthorizationException e) { + String msg = "Error occurred while checking device access authorization"; + log.error(msg, e); + } catch (TrackerManagementDAOException e) { + String msg = "Error occurred while mapping with deviceId ."; + log.error(msg, e); + } catch (ExecutionException e) { + log.error("ExecutionException : " + e); + } catch (InterruptedException e) { + log.error("InterruptedException : " + e); + } + /*Get Device Id List*/ + return Response.status(Response.Status.OK).entity(obj.getString("token")).build(); } }else{ diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Device.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Device.java index 840d155d440..cc35a55c9d0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Device.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Device.java @@ -129,6 +129,10 @@ public class Device implements Serializable { this.deviceStatusInfo = deviceStatusInfo; } + public Device(String deviceId) { + this.deviceIdentifier = deviceId; + } + public int getId() { return id; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerDeviceInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerDeviceInfo.java index 2dafe7a596a..ad55f924298 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerDeviceInfo.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerDeviceInfo.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra (pvt) Ltd. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at @@ -11,11 +11,11 @@ * 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 + * 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; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerGroupInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerGroupInfo.java index 8c722516858..9f7e6b63dee 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerGroupInfo.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerGroupInfo.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra (pvt) Ltd. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at @@ -11,11 +11,11 @@ * 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 + * 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; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerPermissionInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerPermissionInfo.java index cb91e44bcf9..c8509efa291 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerPermissionInfo.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerPermissionInfo.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra (pvt) Ltd. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at @@ -11,11 +11,11 @@ * 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 + * 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; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerUserInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerUserInfo.java index 96d5c5137ed..4985c601fd9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerUserInfo.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerUserInfo.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra (pvt) Ltd. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at @@ -11,11 +11,11 @@ * 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 + * 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; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/exceptions/TrackerAlreadyExistException.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/exceptions/TrackerAlreadyExistException.java index bf27865da97..bc7a92684fb 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/exceptions/TrackerAlreadyExistException.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/exceptions/TrackerAlreadyExistException.java @@ -1,19 +1,19 @@ /* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, - * 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 + * 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 + * 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. + * 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; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java index 8f23228bef9..fcf414ff087 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java @@ -16,21 +16,21 @@ * 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, - * 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 + * 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 + * 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. + * 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; @@ -301,6 +301,16 @@ public interface DeviceDAO { */ List 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 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 * activeServerCount and serverIndex diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerDAO.java index e7a0d635943..3175b3018e8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerDAO.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra (pvt) Ltd. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at @@ -11,17 +11,19 @@ * 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 + * 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 { /** @@ -36,12 +38,12 @@ public interface TrackerDAO { /** * get trackerDevice info. - * @param groupId of the device. + * @param deviceId of the device. * @param tenantId of the group. * @return Tracker Device Info. * @throws TrackerManagementDAOException */ - TrackerDeviceInfo getTrackerDevice(int groupId, int tenantId) throws TrackerManagementDAOException; + TrackerDeviceInfo getTrackerDevice(int deviceId, int tenantId) throws TrackerManagementDAOException; /** * update trackerDevice status and traccarDeviceId. @@ -49,7 +51,7 @@ public interface TrackerDAO { * @param deviceId of the device. * @param tenantId of the group. * @param status of the device. - * @return Tracker Device Info. + * @return boolean value. * @throws TrackerManagementDAOException */ Boolean updateTrackerDeviceIdANDStatus(int traccarDeviceId, int deviceId, int tenantId, int status) throws TrackerManagementDAOException; @@ -86,35 +88,61 @@ public interface TrackerDAO { /** * Remove a Group. - * @param id mapping table. + * @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 mapping table. + * @param deviceId of permissions. + * @return boolean value. * @throws TrackerManagementDAOException */ - Boolean removeTrackerUserDevicePermission(int deviceId) throws TrackerManagementDAOException; + Boolean removeTrackerUserDevicePermission(int deviceId, int userId, int removeType) throws TrackerManagementDAOException; - TrackerPermissionInfo getUserIdofPermissionByDeviceId(int deviceId) throws TrackerManagementDAOException; + /** + * get list of userDevicePermissions by. + * @param deviceId of permissions. + * @return Tracker Permission Info. + * @throws TrackerManagementDAOException + */ + List 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 getUserIdofPermissionByUserIdNIdList(int userId, List NotInDeviceIdList) throws TrackerManagementDAOException; /** - * get trackerGroup info. - * @param groupId of the device. - * @param tenantId of the group. - * @return Tracker Device Info. + * get list of userDevicePermissions by. + * @param deviceId of permissions. + * @param userId of permissions. + * @return Tracker Permission Info. * @throws TrackerManagementDAOException */ - TrackerGroupInfo getTrackerGroup(int groupId, int tenantId) throws TrackerManagementDAOException; + Boolean getUserIdofPermissionByDeviceIdNUserId(int deviceId, int userId) throws TrackerManagementDAOException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerManagementDAOException.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerManagementDAOException.java index 96d81dedbf3..bb0f3cc2a27 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerManagementDAOException.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerManagementDAOException.java @@ -1,19 +1,19 @@ /* - * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, - * 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 + * 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 + * 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. + * 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; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerManagementDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerManagementDAOFactory.java index 0c0a44f20c7..1839425b25a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerManagementDAOFactory.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerManagementDAOFactory.java @@ -1,19 +1,19 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, - * 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 + * 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 + * 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. + * 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; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java index 9e9da571496..542a7a2a071 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java @@ -188,6 +188,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } } + //Return only not removed id list @Override public List getDeviceListWithoutPagination(int tenantId) throws DeviceManagementDAOException { @@ -217,7 +218,82 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } @Override - public List getAllocatedDevices(PaginationRequest request, int tenantId, int activeServerCount, int serverIndex) + public List getDevicesIds(PaginationRequest request, int tenantId) + throws DeviceManagementDAOException { + Connection conn; + List devices = null; + String owner = request.getOwner(); + boolean isOwnerProvided = false; + String ownership = request.getOwnership(); + boolean isOwnershipProvided = false; + List 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 getAllocatedDevices(PaginationRequest request, int tenantId, + int activeServerCount, int serverIndex) throws DeviceManagementDAOException { List devices; String deviceType = request.getDeviceType(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java index beef6f15421..49b4f88c2a3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java @@ -188,6 +188,81 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { } } + //Return only not removed id list + @Override + public List getDevicesIds(PaginationRequest request, int tenantId) + throws DeviceManagementDAOException { + Connection conn; + List devices = null; + String owner = request.getOwner(); + boolean isOwnerProvided = false; + String ownership = request.getOwnership(); + boolean isOwnershipProvided = false; + List 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 getDeviceListWithoutPagination(int tenantId) throws DeviceManagementDAOException { return null; @@ -195,7 +270,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { @Override public List getAllocatedDevices(PaginationRequest request, int tenantId, - int activeServerCount, int serverIndex) + int activeServerCount, int serverIndex) throws DeviceManagementDAOException { Connection conn; List devices = null; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java index eb358004abf..133464a633f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java @@ -179,6 +179,81 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { } } + //Return only not removed id list + @Override + public List getDevicesIds(PaginationRequest request, int tenantId) + throws DeviceManagementDAOException { + Connection conn; + List devices = null; + String owner = request.getOwner(); + boolean isOwnerProvided = false; + String ownership = request.getOwnership(); + boolean isOwnershipProvided = false; + List 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 getDeviceListWithoutPagination(int tenantId) throws DeviceManagementDAOException { return null; @@ -186,7 +261,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { @Override public List getAllocatedDevices(PaginationRequest request, int tenantId, - int activeServerCount, int serverIndex) + int activeServerCount, int serverIndex) throws DeviceManagementDAOException { Connection conn; List devices = null; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java index f9e087e64e2..7686ada7ea7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java @@ -189,6 +189,81 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } } + //Return only not removed id list + @Override + public List getDevicesIds(PaginationRequest request, int tenantId) + throws DeviceManagementDAOException { + Connection conn; + List devices = null; + String owner = request.getOwner(); + boolean isOwnerProvided = false; + String ownership = request.getOwnership(); + boolean isOwnershipProvided = false; + List 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 getDeviceListWithoutPagination(int tenantId) throws DeviceManagementDAOException { return null; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/tracker/TrackerDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/tracker/TrackerDAOImpl.java index 01b533a240e..0be2d2a7982 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/tracker/TrackerDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/tracker/TrackerDAOImpl.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra (pvt) Ltd. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at @@ -11,11 +11,11 @@ * 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 + * 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.wso2.carbon.device.mgt.common.TrackerDeviceInfo; @@ -25,16 +25,20 @@ import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.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 { @Override - public Boolean addTrackerDevice(int traccarDeviceId, int deviceId, int tenantId) throws TrackerManagementDAOException { + public Boolean addTrackerDevice(int traccarDeviceId, int deviceId, int tenantId) + throws TrackerManagementDAOException { PreparedStatement stmt = null; try { Connection conn = TrackerManagementDAOFactory.getConnection(); @@ -47,14 +51,15 @@ public class TrackerDAOImpl implements TrackerDAO { return true; } catch (SQLException e) { - throw new TrackerManagementDAOException("Error occurred while adding traccar device mapping", e); + throw new TrackerManagementDAOException("Error occurred while adding on trackerDevice mapping table", e); } finally { TrackerManagementDAOUtil.cleanupResources(stmt, null); } } @Override - public Boolean updateTrackerDeviceIdANDStatus(int traccarDeviceId, int deviceId, int tenantId, int status) throws TrackerManagementDAOException { + public Boolean updateTrackerDeviceIdANDStatus(int traccarDeviceId, int deviceId, int tenantId, int status) + throws TrackerManagementDAOException { PreparedStatement stmt = null; try { Connection conn = TrackerManagementDAOFactory.getConnection(); @@ -68,7 +73,7 @@ public class TrackerDAOImpl implements TrackerDAO { return true; } catch (SQLException e) { - String msg = "Error occurred while updating trackerDevice mapping table"; + String msg = "Error occurred while updating status on trackerDevice mapping table"; throw new TrackerManagementDAOException(msg, e); } finally { TrackerManagementDAOUtil.cleanupResources(stmt, null); @@ -93,7 +98,7 @@ public class TrackerDAOImpl implements TrackerDAO { } return status; } catch (SQLException e) { - throw new TrackerManagementDAOException("Error occurred while removing trackerDevice", e); + throw new TrackerManagementDAOException("Error occurred while removing on trackerDevice table", e); } finally { TrackerManagementDAOUtil.cleanupResources(stmt, null); } @@ -113,18 +118,19 @@ public class TrackerDAOImpl implements TrackerDAO { stmt.setInt(2, tenantId); rs = stmt.executeQuery(); if (rs.next()) { - trackerDeviceInfo = this.loadTrackerDevice(rs); + trackerDeviceInfo = TrackerManagementDAOUtil.loadTrackerDevice(rs); } return trackerDeviceInfo; } catch (SQLException e) { - throw new TrackerManagementDAOException("Error occurred while retrieving the trackerDevice information ", e); + throw new TrackerManagementDAOException("Error occurred while retrieving data from the trackerDevice table ", e); } finally { TrackerManagementDAOUtil.cleanupResources(stmt, rs); } } @Override - public Boolean addTrackerGroup(int traccarGroupId, int groupId, int tenantId) throws TrackerManagementDAOException { + public Boolean addTrackerGroup(int traccarGroupId, int groupId, int tenantId) + throws TrackerManagementDAOException { PreparedStatement stmt = null; int status = 1 ; try { @@ -139,7 +145,7 @@ public class TrackerDAOImpl implements TrackerDAO { return true; } catch (SQLException e) { - String msg = "Error occurred while adding traccar group mapping"; + String msg = "Error occurred while adding on traccarGroup mapping table"; throw new TrackerManagementDAOException(msg, e); } finally { TrackerManagementDAOUtil.cleanupResources(stmt, null); @@ -147,7 +153,8 @@ public class TrackerDAOImpl implements TrackerDAO { } @Override - public Boolean updateTrackerGroupIdANDStatus(int traccarGroupId, int groupId, int tenantId, int status) throws TrackerManagementDAOException { + public Boolean updateTrackerGroupIdANDStatus(int traccarGroupId, int groupId, int tenantId, int status) + throws TrackerManagementDAOException { PreparedStatement stmt = null; try { Connection conn = TrackerManagementDAOFactory.getConnection(); @@ -161,7 +168,7 @@ public class TrackerDAOImpl implements TrackerDAO { return true; } catch (SQLException e) { - String msg = "Error occurred while updating traccar group mapping table"; + String msg = "Error occurred while updating status on traccarGroup mapping table"; throw new TrackerManagementDAOException(msg, e); } finally { TrackerManagementDAOUtil.cleanupResources(stmt, null); @@ -185,7 +192,7 @@ public class TrackerDAOImpl implements TrackerDAO { } return status; } catch (SQLException e) { - throw new TrackerManagementDAOException("Error occurred while removing traccar group", e); + throw new TrackerManagementDAOException("Error occurred while removing from traccarGroup mapping table", e); } finally { TrackerManagementDAOUtil.cleanupResources(stmt, null); } @@ -205,18 +212,19 @@ public class TrackerDAOImpl implements TrackerDAO { stmt.setInt(2, tenantId); rs = stmt.executeQuery(); if (rs.next()) { - trackerGroupInfo = this.loadTrackerGroup(rs); + trackerGroupInfo = TrackerManagementDAOUtil.loadTrackerGroup(rs); } return trackerGroupInfo; } catch (SQLException e) { - throw new TrackerManagementDAOException("Error occurred while retrieving the traccar group information ", e); + throw new TrackerManagementDAOException("Error occurred while retrieving data from the traccarGroup mapping table ", e); } finally { TrackerManagementDAOUtil.cleanupResources(stmt, rs); } } @Override - public Boolean addTrackerUserDevicePermission(int traccarUserId, int deviceId) throws TrackerManagementDAOException { + public Boolean addTrackerUserDevicePermission(int traccarUserId, int deviceId) + throws TrackerManagementDAOException { PreparedStatement stmt = null; try { Connection conn = TrackerManagementDAOFactory.getConnection(); @@ -228,78 +236,121 @@ public class TrackerDAOImpl implements TrackerDAO { return true; } catch (SQLException e) { - throw new TrackerManagementDAOException("Error occurred while adding traccar user device mapping", e); + throw new TrackerManagementDAOException("Error occurred while adding permission on permissions mapping table", e); } finally { TrackerManagementDAOUtil.cleanupResources(stmt, null); } } @Override - public Boolean removeTrackerUserDevicePermission(int deviceId) throws TrackerManagementDAOException { + 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=?"; + 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) { - throw new TrackerManagementDAOException("Error occurred while removing traccar user device permission mapping", e); + throw new TrackerManagementDAOException("Error occurred while removing permission from permissions mapping table", e); } finally { TrackerManagementDAOUtil.cleanupResources(stmt, null); } } @Override - public TrackerPermissionInfo getUserIdofPermissionByDeviceId(int deviceId) throws TrackerManagementDAOException { + public List getUserIdofPermissionByDeviceId(int deviceId) + throws TrackerManagementDAOException { PreparedStatement stmt = null; ResultSet rs = null; - TrackerPermissionInfo trackerPermissionInfo = null; + List 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 DESC LIMIT 1"; + "TRACCAR_DEVICE_ID = ? ORDER BY TRACCAR_DEVICE_ID ASC"; stmt = conn.prepareStatement(sql); stmt.setInt(1, deviceId); rs = stmt.executeQuery(); - if (rs.next()) { - trackerPermissionInfo = this.loadPermission(rs); + trackerPermissionInfo = new ArrayList<>(); + while (rs.next()) { + TrackerPermissionInfo loadPermission = TrackerManagementDAOUtil.loadPermission(rs); + trackerPermissionInfo.add(loadPermission); } return trackerPermissionInfo; } catch (SQLException e) { - throw new TrackerManagementDAOException("Error occurred while retrieving the traccar group information ", e); + throw new TrackerManagementDAOException("Error occurred while retrieving permissions data from permissions mapping table ", e); } finally { TrackerManagementDAOUtil.cleanupResources(stmt, rs); } } + @Override + public List getUserIdofPermissionByUserIdNIdList(int userId, List NotInDeviceIdList) + throws TrackerManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + List 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"; - private TrackerGroupInfo loadTrackerGroup(ResultSet rs) throws SQLException { - TrackerGroupInfo trackerGroupInfo = new TrackerGroupInfo(); - trackerGroupInfo.setId(rs.getInt("ID")); - trackerGroupInfo.setTraccarGroupId(rs.getInt("TRACCAR_GROUP_ID")); - trackerGroupInfo.setGroupId(rs.getInt("GROUP_ID")); - trackerGroupInfo.setTenantId(rs.getInt("TENANT_ID")); - trackerGroupInfo.setStatus(rs.getInt("STATUS")); - return trackerGroupInfo; + 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 "; + throw new TrackerManagementDAOException(msg, e); + } finally { + TrackerManagementDAOUtil.cleanupResources(stmt, rs); + } } - private TrackerDeviceInfo loadTrackerDevice(ResultSet rs) throws SQLException { - TrackerDeviceInfo trackerDeviceInfo = new TrackerDeviceInfo(); - trackerDeviceInfo.setId(rs.getInt("ID")); - trackerDeviceInfo.setTraccarDeviceId(rs.getInt("TRACCAR_DEVICE_ID")); - trackerDeviceInfo.setDeviceId(rs.getInt("DEVICE_ID")); - trackerDeviceInfo.setTenantId(rs.getInt("TENANT_ID")); - trackerDeviceInfo.setStatus(rs.getInt("STATUS")); - return trackerDeviceInfo; - } + @Override + public Boolean getUserIdofPermissionByDeviceIdNUserId(int deviceId, int userId) throws TrackerManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + TrackerPermissionInfo trackerPermissionInfo = null; + try { + Connection conn = TrackerManagementDAOFactory.getConnection(); + String sql = "SELECT TRACCAR_DEVICE_ID, TRACCAR_USER_ID FROM DM_EXT_PERMISSION_MAPPING WHERE " + + "TRACCAR_DEVICE_ID = ? AND TRACCAR_USER_ID = ? ORDER BY TRACCAR_DEVICE_ID DESC"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, deviceId); + stmt.setInt(2, userId); - private TrackerPermissionInfo loadPermission(ResultSet rs) throws SQLException { - TrackerPermissionInfo trackerPermissionInfo = new TrackerPermissionInfo(); - trackerPermissionInfo.setTraccarUserId(rs.getInt("TRACCAR_USER_ID")); - trackerPermissionInfo.setTraccarDeviceId(rs.getInt("TRACCAR_DEVICE_ID")); - return trackerPermissionInfo; + rs = stmt.executeQuery(); + return rs.next(); + } catch (SQLException e) { + throw new TrackerManagementDAOException("Error occurred while retrieving permissions data from permissions mapping table ", e); + } finally { + TrackerManagementDAOUtil.cleanupResources(stmt, rs); + } } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java index 1f031e7c4e0..91b549d9e63 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java @@ -173,6 +173,14 @@ public final class DeviceManagementDAOUtil { 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 { Map enrolmentInfos = new HashMap<>(); EnrolmentInfo enrolmentInfo = loadEnrolment(rs); @@ -218,6 +226,14 @@ public final class DeviceManagementDAOUtil { 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 { DeviceBilling device = new DeviceBilling(); device.setId(rs.getInt("ID")); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/TrackerManagementDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/TrackerManagementDAOUtil.java index 7aab01a40a4..117b994762c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/TrackerManagementDAOUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/TrackerManagementDAOUtil.java @@ -14,28 +14,32 @@ * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. + */ +/* Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. * - * Copyright (c) 2021, Entgra (pvt) Ltd. (https://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 + * 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 + * 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. + * 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; @@ -43,6 +47,8 @@ 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 @@ -81,8 +87,7 @@ public final class TrackerManagementDAOUtil { * @param jndiProperties Hash table of JNDI Properties * @return datasource looked */ - public static DataSource lookupDataSource(String dataSourceName, - final Hashtable jndiProperties) { + public static DataSource lookupDataSource(String dataSourceName, final Hashtable jndiProperties) { try { if (jndiProperties == null || jndiProperties.isEmpty()) { return (DataSource) InitialContext.doLookup(dataSourceName); @@ -93,4 +98,42 @@ public final class TrackerManagementDAOUtil { throw new RuntimeException("Error in looking up data source: " + e.getMessage(), e); } } + + 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 DeviceIdList) throws TrackerManagementDAOException { + if (DeviceIdList == null || DeviceIdList.isEmpty()) { + String msg = "SQL query build for Device Id list failed. Device Id list cannot be empty or null"; + throw new TrackerManagementDAOException(msg); + } + StringJoiner joiner = new StringJoiner(",", " AND TRACCAR_DEVICE_ID NOT IN(", ")"); + DeviceIdList.stream().map(status -> "?").forEach(joiner::add); + + return joiner.toString(); + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java index 438f118b2d8..a5bc8b40969 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java @@ -399,6 +399,8 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { log.error("InterruptedException : " + e); //throw new RuntimeException(e); } + }else{ + log.info("location publishing is disabled and traccan disabled"); } //Tracker update GPS Location diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java index 851bb3050c9..a84deb88944 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java @@ -67,7 +67,6 @@ import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.dto.DeviceTypeVersion; import org.wso2.carbon.device.mgt.common.geo.service.GeoCluster; -import java.io.IOException; import java.sql.SQLException; import java.sql.Timestamp; import java.util.Collection; @@ -187,6 +186,16 @@ public interface DeviceManagementProviderService { */ 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. * @@ -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. * diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 4488f4da3ad..53cab62fc0b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -32,6 +32,7 @@ * specific language governing permissions and limitations * under the License. */ + package org.wso2.carbon.device.mgt.core.service; import com.google.common.reflect.TypeToken; @@ -173,7 +174,6 @@ import java.util.Properties; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; - public class DeviceManagementProviderServiceImpl implements DeviceManagementProviderService, PluginInitializationListener { @@ -1226,6 +1226,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv return paginationResult; } + @Override + public PaginationResult getAllDevicesIds(PaginationRequest request) throws DeviceManagementException { + return this.getAllDevicesIdList(request); + } + @Override public PaginationResult getAllDevices(PaginationRequest request, boolean requireDeviceInfo) throws DeviceManagementException { if (request == null) { @@ -1286,6 +1291,48 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv 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 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 public Device getDevice(DeviceIdentifier deviceId, boolean requireDeviceInfo) throws DeviceManagementException { if (deviceId == null) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/TraccarClient.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/TraccarClient.java index c44162a30a0..c74db398ac6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/TraccarClient.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/TraccarClient.java @@ -19,25 +19,29 @@ package org.wso2.carbon.device.mgt.core.traccar.api.service; -import org.json.JSONObject; +import org.wso2.carbon.device.mgt.common.TrackerDeviceInfo; +import org.wso2.carbon.device.mgt.common.TrackerPermissionInfo; import org.wso2.carbon.device.mgt.common.exceptions.TrackerAlreadyExistException; +import org.wso2.carbon.device.mgt.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 fetchAllDevices() throws TraccarConfigurationException, ExecutionException, InterruptedException; + //String fetchDevicesByUniqueId(String uniqueId) throws ExecutionException, InterruptedException; void addDevice(TraccarDevice deviceInfo, int tenantId) throws - TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException; + TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException, TrackerManagementDAOException; void updateLocation(TraccarDevice device, TraccarPosition deviceInfo, int tenantId) throws - TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException; + TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException, TrackerManagementDAOException; void disEnrollDevice(int traccarDeviceId, int tenantId) throws TraccarConfigurationException; @@ -49,9 +53,15 @@ public interface TraccarClient { void deleteGroup(int traccarGroupId, int tenantId) throws TraccarConfigurationException, ExecutionException, InterruptedException; - void setPermission(int userId, int deviceId) throws TraccarConfigurationException, ExecutionException, InterruptedException; + void setPermission(int userId, int deviceId) throws TrackerManagementDAOException, ExecutionException, InterruptedException; + + void removePermission(int userId, int deviceId, int removeType) throws ExecutionException, InterruptedException; + + List getUserIdofPermissionByUserIdNIdList(int userId, List NotInDeviceIdList) throws TrackerManagementDAOException; + + boolean getUserIdofPermissionByDeviceIdNUserId(int deviceId, int userId) throws TraccarConfigurationException, SQLException, TrackerManagementDAOException; - void removePermission(int userId, int deviceId) throws TraccarConfigurationException, ExecutionException, InterruptedException; + TrackerDeviceInfo getTrackerDevice(int deviceId, int tenantId) throws TraccarConfigurationException, SQLException, TrackerManagementDAOException; String fetchAllUsers() throws TraccarConfigurationException, ExecutionException, InterruptedException; @@ -61,5 +71,5 @@ public interface TraccarClient { String updateUser(TraccarUser traccarUser, int userId) throws ExecutionException, InterruptedException; - String returnUser(String userName) throws TraccarConfigurationException; + String returnUser(String userName) throws TraccarConfigurationException, TrackerManagementDAOException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java index 7b3458bbcf3..09c9f4c69de 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java @@ -55,6 +55,7 @@ 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; @@ -114,7 +115,13 @@ public class TraccarClientImpl implements TraccarClient { requestBody = RequestBody.create(payload.toString(), MediaType.parse("application/json; charset=utf-8")); builder = builder.put(requestBody); }else if(Objects.equals(method, TraccarHandlerConstants.Methods.DELETE)){ - builder = builder.delete(); + log.info("publisherUrlWithContext - " + publisherUrlWithContext); + if(publisherUrlWithContext.indexOf("permission") !=-1){ + requestBody = RequestBody.create(payload.toString(), MediaType.parse("application/json; charset=utf-8")); + builder = builder.delete(requestBody); + }else{ + builder = builder.delete(); + } } request = builder.url(endpoint+publisherUrlWithContext).addHeader(authorization, authorizationKey).build(); @@ -150,7 +157,7 @@ public class TraccarClientImpl implements TraccarClient { return TraccarHandlerConstants.Types.USER_NOT_FOUND; } - public String returnUser(String userName) throws TraccarConfigurationException{ + public String returnUser(String userName) throws TrackerManagementDAOException{ try{ String result = DeviceAPIClientServiceImpl.fetchUserInfo(userName); Date today = new Date(); @@ -227,7 +234,7 @@ public class TraccarClientImpl implements TraccarClient { return result; } - public void setPermission(int userId, int deviceId) throws TraccarConfigurationException, ExecutionException, InterruptedException { + public void setPermission(int userId, int deviceId) throws ExecutionException, InterruptedException, TrackerManagementDAOException { JSONObject payload = new JSONObject(); payload.put("userId", userId); payload.put("deviceId", deviceId); @@ -247,12 +254,12 @@ public class TraccarClientImpl implements TraccarClient { TrackerManagementDAOFactory.rollbackTransaction(); String msg = "Error occurred while mapping with deviceId ."; log.error(msg, e); - throw new TraccarConfigurationException(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 TraccarConfigurationException(msg, e); + throw new TrackerManagementDAOException(msg, e); } finally { TrackerManagementDAOFactory.closeConnection(); } @@ -261,7 +268,7 @@ public class TraccarClientImpl implements TraccarClient { } } - public void removePermission(int userId, int deviceId) throws TraccarConfigurationException, ExecutionException, InterruptedException { + public void removePermission(int userId, int deviceId, int removeType) throws ExecutionException, InterruptedException { JSONObject payload = new JSONObject(); payload.put("userId", userId); payload.put("deviceId", deviceId); @@ -276,32 +283,76 @@ public class TraccarClientImpl implements TraccarClient { if(result!=null){ try { TrackerManagementDAOFactory.beginTransaction(); - trackerDAO.removeTrackerUserDevicePermission(deviceId); + 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); + //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); + //throw new TraccarConfigurationException(msg, e); } finally { TrackerManagementDAOFactory.closeConnection(); } } } - public String fetchAllDevices() throws ExecutionException, InterruptedException { - String method = TraccarHandlerConstants.Methods.GET; - String url = defaultPort+"/api/devices"; + public List getUserIdofPermissionByUserIdNIdList(int userId, List 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(); + } + } - Future result = executor.submit(new OkHttpClientThreadPool(url, null, method)); - String res = result.get(); - //executor.shutdown(); - return res; + 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; } /** @@ -311,7 +362,7 @@ public class TraccarClientImpl implements TraccarClient { * @throws TraccarConfigurationException Failed while add Traccar Device the operation */ public void addDevice(TraccarDevice traccarDevice, int tenantId) throws - TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException { + TrackerAlreadyExistException, ExecutionException, InterruptedException, TrackerManagementDAOException { TrackerDeviceInfo trackerDeviceInfo = null; try { TrackerManagementDAOFactory.openConnection(); @@ -324,11 +375,11 @@ public class TraccarClientImpl implements TraccarClient { } catch (TrackerManagementDAOException e) { String msg = "Error occurred while mapping with deviceId ."; log.error(msg, e); - throw new TraccarConfigurationException(msg, e); + throw new TrackerManagementDAOException(msg, e); } catch (SQLException e) { String msg = "Error occurred establishing the DB connection ."; log.error(msg, e); - throw new TraccarConfigurationException(msg, e); + throw new TrackerManagementDAOException(msg, e); } finally { TrackerManagementDAOFactory.closeConnection(); } @@ -341,11 +392,14 @@ public class TraccarClientImpl implements TraccarClient { Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method)); String result = res.get(); + log.info("---------res--------" + 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); + log.info("DeviceId - " + deviceId); try { TrackerManagementDAOFactory.beginTransaction(); trackerDAO.addTrackerDevice(traccarDeviceId, deviceId, tenantId); @@ -358,12 +412,12 @@ public class TraccarClientImpl implements TraccarClient { TrackerManagementDAOFactory.rollbackTransaction(); String msg = "Error occurred while mapping with deviceId ."; log.error(msg, e); - throw new TraccarConfigurationException(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 TraccarConfigurationException(msg, e); + throw new TrackerManagementDAOException(msg, e); } finally { TrackerManagementDAOFactory.closeConnection(); } @@ -380,7 +434,7 @@ public class TraccarClientImpl implements TraccarClient { * 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 TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException { + public void updateLocation(TraccarDevice device, TraccarPosition deviceInfo, int tenantId) throws TrackerManagementDAOException, TrackerAlreadyExistException, ExecutionException, InterruptedException { TrackerDeviceInfo trackerDeviceInfo = null; try { TrackerManagementDAOFactory.openConnection(); @@ -388,11 +442,11 @@ public class TraccarClientImpl implements TraccarClient { } catch (SQLException e) { String msg = "Error occurred establishing the DB connection ."; log.error(msg, e); - throw new TraccarConfigurationException(msg, e); + throw new TrackerManagementDAOException(msg, e); } catch (TrackerManagementDAOException e) { String msg="Could not add new device location"; log.error(msg, e); - throw new TraccarConfigurationException(msg, e); + throw new TrackerManagementDAOException(msg, e); } finally{ TrackerManagementDAOFactory.closeConnection(); } @@ -421,21 +475,25 @@ public class TraccarClientImpl implements TraccarClient { */ public void disEnrollDevice(int deviceId, int tenantId) throws TraccarConfigurationException { TrackerDeviceInfo trackerDeviceInfo = null; - TrackerPermissionInfo trackerPermissionInfo = null; - JSONObject trackerDevice = null; - + List trackerPermissionInfo = null; + //JSONObject trackerDevice = null; + try { TrackerManagementDAOFactory.beginTransaction(); trackerDeviceInfo = trackerDAO.getTrackerDevice(deviceId, tenantId); + + log.info("------deviceId-----" + deviceId); + log.info(trackerDeviceInfo); + log.info(new Gson().toJson(trackerDeviceInfo)); + log.info(trackerDeviceInfo.getDeviceId()); + log.info(trackerDeviceInfo.getTraccarDeviceId()); if(trackerDeviceInfo!=null){ - trackerDevice = new JSONObject(trackerDeviceInfo); - trackerDAO.removeTrackerDevice(deviceId, tenantId); + //trackerDevice = new JSONObject(trackerDeviceInfo); + int status = trackerDAO.removeTrackerDevice(deviceId, tenantId); + log.info("Status" + status); TrackerManagementDAOFactory.commitTransaction(); - log.error(trackerDevice.getInt("traccarDeviceId")); - trackerPermissionInfo = trackerDAO.getUserIdofPermissionByDeviceId(trackerDevice.getInt("traccarDeviceId")); - log.error(trackerPermissionInfo); - log.error(new Gson().toJson(trackerPermissionInfo)); + trackerPermissionInfo = trackerDAO.getUserIdofPermissionByDeviceId(trackerDeviceInfo.getTraccarDeviceId()); } } catch (TransactionManagementException e) { TrackerManagementDAOFactory.rollbackTransaction(); @@ -451,24 +509,32 @@ public class TraccarClientImpl implements TraccarClient { TrackerManagementDAOFactory.closeConnection(); } + log.info("__________________"); + log.info(new Gson().toJson(trackerPermissionInfo)); + log.info(trackerPermissionInfo.get(0)); + log.info(new Gson().toJson(trackerPermissionInfo.get(0))); + log.info("__________________"); //Delete from traccar - if(trackerDevice!=null){ + if(trackerDeviceInfo!=null){ String method = TraccarHandlerConstants.Methods.DELETE; - String url = defaultPort+"/api/devices/"+trackerDevice.getInt("traccarDeviceId"); + String url = defaultPort+"/api/devices/"+trackerPermissionInfo.get(0).getTraccarDeviceId(); + //executor.submit(new OkHttpClientThreadPool(url, null, method)); + executor.submit(new OkHttpClientThreadPool(url, null, method)); //executor.shutdown(); - //remove permissions - if(trackerPermissionInfo!=null){ - try { - removePermission(trackerPermissionInfo.getTraccarUserId(),trackerDevice.getInt("traccarDeviceId")); - } catch (ExecutionException e) { - log.error("ExecutionException : " + e); - //throw new RuntimeException(e); - } catch (InterruptedException e) { - log.error("InterruptedException : " + e); - //throw new RuntimeException(e); - } + //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); } } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java index 9b41a1f8b45..a8d4ee85ce5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java @@ -23,9 +23,12 @@ 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.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; @@ -35,6 +38,7 @@ import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarUser; import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarConfigurationException; import java.util.Date; +import java.util.List; import java.util.concurrent.ExecutionException; public class DeviceAPIClientServiceImpl implements DeviceAPIClientService { @@ -49,7 +53,7 @@ public class DeviceAPIClientServiceImpl implements DeviceAPIClientService { "", ""); try { client.addDevice(traccarDevice, tenantId); - } catch (TraccarConfigurationException e) { + } catch (TrackerManagementDAOException e) { String msg = "Error occurred while mapping with deviceId"; log.error(msg, e); } catch (TrackerAlreadyExistException e) { @@ -71,7 +75,7 @@ public class DeviceAPIClientServiceImpl implements DeviceAPIClientService { "", ""); try { client.updateLocation(traccarDevice, traccarPosition, tenantId); - } catch (TraccarConfigurationException e) { + } catch (TrackerManagementDAOException e) { String msg = "Error occurred while mapping with deviceId"; log.error(msg, e); }catch (TrackerAlreadyExistException e) { @@ -109,20 +113,31 @@ public class DeviceAPIClientServiceImpl implements DeviceAPIClientService { client.deleteGroup(groupId, tenantId); } - public static String fetchUserInfo(String userName) throws - TraccarConfigurationException, ExecutionException, InterruptedException { + 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 - TraccarConfigurationException, ExecutionException, InterruptedException { + TrackerManagementDAOException, ExecutionException, InterruptedException { TraccarClientImpl client = new TraccarClientImpl(); return client.createUser(traccarUser); } public static String updateUser(TraccarUser traccarUser, int userId) throws - TraccarConfigurationException, ExecutionException, InterruptedException { + TrackerManagementDAOException, ExecutionException, InterruptedException { TraccarClientImpl client = new TraccarClientImpl(); return client.updateUser(traccarUser, userId); } @@ -131,7 +146,7 @@ public class DeviceAPIClientServiceImpl implements DeviceAPIClientService { TraccarClientImpl client = new TraccarClientImpl(); try { return client.returnUser(userName); - } catch (TraccarConfigurationException e) { + } catch (TrackerManagementDAOException e) { JSONObject obj = new JSONObject(); String msg = "Error occurred while creating a user: "+ e; obj.put("error", msg); @@ -139,6 +154,22 @@ public class DeviceAPIClientServiceImpl implements DeviceAPIClientService { } } + public static void addTrackerUserDevicePermission(int userId, int deviceId) throws + TrackerManagementDAOException, ExecutionException, InterruptedException { + TraccarClientImpl client = new TraccarClientImpl(); + client.setPermission(userId, deviceId); + } + + public static void removeTrackerUserDevicePermission(int userId, int deviceId, int removeType) throws TrackerManagementDAOException, ExecutionException, InterruptedException { + TraccarClientImpl client = new TraccarClientImpl(); + client.removePermission(userId, deviceId, removeType); + } + + public static List getUserIdofPermissionByUserIdNIdList(int userId, List 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); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarHandlerConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarHandlerConstants.java index 7b40c630071..453fb5290fe 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarHandlerConstants.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarHandlerConstants.java @@ -44,18 +44,12 @@ public class TraccarHandlerConstants { public static final String USER = "USER"; public static final String PERMISSION = "PERMISSION"; - public static final String USER_CREATE = "USER_CREATE"; - public static final String USER_CREATE_WITH_INSERT_DEVICE = "USER_CREATE_WITH_INSERT_DEVICE"; - public static final String USER_UPDATE = "USER_UPDATE"; - public static final String USER_UPDATE_WITH_INSERT_DEVICE = "USER_UPDATE_WITH_INSERT_DEVICE"; - public static final String USER_SEARCH = "USER_SEARCH"; - public static final String FETCH_ALL_USERS = "FETCH_ALL_USERS"; - public static final String FETCH_ALL_DEVICES = "FETCH_ALL_DEVICES"; - public static final String USER_NOT_FOUND = "USER_NOT_FOUND"; public static final 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; } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarUser.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarUser.java index 551658be722..37557ef0948 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarUser.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarUser.java @@ -16,6 +16,7 @@ * under the License. * */ + package org.wso2.carbon.device.mgt.core.traccar.common.beans; import java.io.Serializable; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/TraccarConfigurationException.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/TraccarConfigurationException.java index 748f6e0f79b..ba601140411 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/TraccarConfigurationException.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/TraccarConfigurationException.java @@ -1,17 +1,18 @@ /* - * Copyright (c) 2020, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (C) 2018 - 2022 Entgra (Pvt) Ltd, Inc - All Rights Reserved. * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. + * 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 * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://entgra.io/licenses/entgra-commercial/1.0 * * Unless required by applicable law or agreed to in writing, * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/util/TraccarUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/util/TraccarUtil.java index 9147ccc106a..95aea15585c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/util/TraccarUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/util/TraccarUtil.java @@ -1,3 +1,22 @@ +/* + * Copyright (C) 2018 - 2022 Entgra (Pvt) Ltd, Inc - All Rights Reserved. + * + * Unauthorised copying/redistribution of this file, via any medium is strictly prohibited. + * + * Licensed under the Entgra Commercial License, Version 1.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://entgra.io/licenses/entgra-commercial/1.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + package org.wso2.carbon.device.mgt.core.traccar.common.util; import org.json.JSONObject; From 9f642701ea52dfef52f86a50296b2c3af0e11e87 Mon Sep 17 00:00:00 2001 From: Rushdi Date: Mon, 30 May 2022 17:33:07 +0530 Subject: [PATCH 27/41] fix merge conflicts --- .../carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java | 1 + 1 file changed, 1 insertion(+) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java index e5be89f9127..230a958d198 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java @@ -31,6 +31,7 @@ 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.PostgreSQLDeviceDAOImpl; import org.wso2.carbon.device.mgt.core.dao.impl.device.SQLServerDeviceDAOImpl; +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.device.details.mgt.dao.DeviceDetailsDAO; import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.impl.DeviceDetailsDAOImpl; From ab332e20eda90896818ca27718e6731346bdff8c Mon Sep 17 00:00:00 2001 From: Rushdi Date: Fri, 3 Jun 2022 16:11:18 +0530 Subject: [PATCH 28/41] Fix platform configuration for traccar --- .../api/service/addons/TraccarClientImpl.java | 85 +++++++++++++++---- .../mgt/core/util/HttpReportingUtil.java | 27 ++++++ 2 files changed, 96 insertions(+), 16 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java index 09c9f4c69de..53350753179 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java @@ -26,6 +26,7 @@ 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; @@ -50,6 +51,7 @@ import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarConfiguratio 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; @@ -94,11 +96,22 @@ public class TraccarClientImpl implements TraccarClient { final String publisherUrlWithContext; final JSONObject payload; private final String method; + private String authorizeKey; + private String serverUri; - private OkHttpClientThreadPool(String publisherUrlWithContext, JSONObject payload, String method) { + 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 @@ -115,7 +128,6 @@ public class TraccarClientImpl implements TraccarClient { requestBody = RequestBody.create(payload.toString(), MediaType.parse("application/json; charset=utf-8")); builder = builder.put(requestBody); }else if(Objects.equals(method, TraccarHandlerConstants.Methods.DELETE)){ - log.info("publisherUrlWithContext - " + publisherUrlWithContext); if(publisherUrlWithContext.indexOf("permission") !=-1){ requestBody = RequestBody.create(payload.toString(), MediaType.parse("application/json; charset=utf-8")); builder = builder.delete(requestBody); @@ -124,7 +136,7 @@ public class TraccarClientImpl implements TraccarClient { } } - request = builder.url(endpoint+publisherUrlWithContext).addHeader(authorization, authorizationKey).build(); + request = builder.url(serverUri+publisherUrlWithContext).addHeader(authorization, authorizeKey).build(); response = client.newCall(request).execute(); return response.body().string(); } @@ -134,7 +146,9 @@ public class TraccarClientImpl implements TraccarClient { String method = TraccarHandlerConstants.Methods.GET; String url = defaultPort+"/api/users"; - Future result = executor.submit(new OkHttpClientThreadPool(url, null, method)); + Future result = executor.submit(new OkHttpClientThreadPool(url, null, method, + authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), + serverUrl(HttpReportingUtil.trackerServer()))); String res = result.get(); //executor.shutdown(); return res; @@ -174,7 +188,7 @@ public class TraccarClientImpl implements TraccarClient { traccarUser.setEmail(userName); traccarUser.setPassword(DeviceAPIClientServiceImpl.generateRandomString(TraccarHandlerConstants.Types.DEFAULT_RANDOM)); traccarUser.setDeviceLimit(-1); - traccarUser.setUserLimit(-1); + //traccarUser.setUserLimit(-1); traccarUser.setExpirationTime(tomorrow.toString()); DeviceAPIClientServiceImpl.createUser(traccarUser); }else{ @@ -216,7 +230,9 @@ public class TraccarClientImpl implements TraccarClient { String url = defaultPort+"/api/users"; JSONObject payload = TraccarUtil.TraccarUserPayload(traccarUser); - Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method)); + Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method, + authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), + serverUrl(HttpReportingUtil.trackerServer()))); String result = res.get(); //executor.shutdown(); @@ -228,7 +244,9 @@ public class TraccarClientImpl implements TraccarClient { String url = defaultPort+"/api/users/"+userId; JSONObject payload = TraccarUtil.TraccarUserPayload(traccarUser); - Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method)); + Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method, + authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), + serverUrl(HttpReportingUtil.trackerServer()))); String result = res.get(); //executor.shutdown(); return result; @@ -242,7 +260,9 @@ public class TraccarClientImpl implements TraccarClient { String method = TraccarHandlerConstants.Methods.POST; String url = defaultPort+"/api/permissions"; - Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method)); + Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method, + authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), + serverUrl(HttpReportingUtil.trackerServer()))); String result = res.get(); //executor.shutdown(); if(result==""){ @@ -276,7 +296,9 @@ public class TraccarClientImpl implements TraccarClient { String method = TraccarHandlerConstants.Methods.DELETE; String url = defaultPort+"/api/permissions"; - Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method)); + Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method, + authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), + serverUrl(HttpReportingUtil.trackerServer()))); String result = res.get(); //executor.shutdown(); @@ -390,7 +412,9 @@ public class TraccarClientImpl implements TraccarClient { String url = defaultPort+"/api/devices"; JSONObject payload = TraccarUtil.TraccarDevicePayload(traccarDevice); - Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method)); + Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method, + authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), + serverUrl(HttpReportingUtil.trackerServer()))); String result = res.get(); log.info("---------res--------" + result); if(result.charAt(0)=='{'){ @@ -463,7 +487,9 @@ public class TraccarClientImpl implements TraccarClient { "&lon="+deviceInfo.getLon()+"&bearing="+deviceInfo.getBearing()+ "&speed="+deviceInfo.getSpeed()+"&ignition=true"; - executor.submit(new OkHttpClientThreadPool(url, null, method)); + executor.submit(new OkHttpClientThreadPool(url, null, method, + authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), + serverUrl(HttpReportingUtil.trackerServer()))); //executor.shutdown(); } } @@ -518,9 +544,10 @@ public class TraccarClientImpl implements TraccarClient { if(trackerDeviceInfo!=null){ String method = TraccarHandlerConstants.Methods.DELETE; String url = defaultPort+"/api/devices/"+trackerPermissionInfo.get(0).getTraccarDeviceId(); - //executor.submit(new OkHttpClientThreadPool(url, null, method)); - executor.submit(new OkHttpClientThreadPool(url, null, method)); + executor.submit(new OkHttpClientThreadPool(url, null, method, + authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), + serverUrl(HttpReportingUtil.trackerServer()))); //executor.shutdown(); //remove permissions @@ -574,7 +601,9 @@ public class TraccarClientImpl implements TraccarClient { String method = TraccarHandlerConstants.Methods.POST; String url = defaultPort+"/api/groups"; - Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method)); + Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method, + authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), + serverUrl(HttpReportingUtil.trackerServer()))); String result = res.get(); if(result.charAt(0)=='{'){ @@ -664,7 +693,9 @@ public class TraccarClientImpl implements TraccarClient { String method = TraccarHandlerConstants.Methods.PUT; String url = defaultPort+"/api/groups/"+obj.getInt("traccarGroupId"); - executor.submit(new OkHttpClientThreadPool(url, payload, method)); + executor.submit(new OkHttpClientThreadPool(url, payload, method, + authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), + serverUrl(HttpReportingUtil.trackerServer()))); //executor.shutdown(); } } @@ -689,7 +720,9 @@ public class TraccarClientImpl implements TraccarClient { String method = TraccarHandlerConstants.Methods.DELETE; String url = defaultPort+"/api/groups/"+obj.getInt("traccarGroupId"); - executor.submit(new OkHttpClientThreadPool(url, null, method)); + executor.submit(new OkHttpClientThreadPool(url, null, method, + authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), + serverUrl(HttpReportingUtil.trackerServer()))); //executor.shutdown(); } } @@ -719,4 +752,24 @@ public class TraccarClientImpl implements TraccarClient { 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; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/HttpReportingUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/HttpReportingUtil.java index b03510e5c83..139eb00430d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/HttpReportingUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/HttpReportingUtil.java @@ -36,6 +36,9 @@ public class HttpReportingUtil { 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() { return System.getProperty(DeviceManagementConstants.Report.REPORTING_EVENT_HOST); @@ -80,4 +83,28 @@ public class HttpReportingUtil { } 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; + } } From f61ab0ae695b654a23d3f688c562adae76a5442b Mon Sep 17 00:00:00 2001 From: Rushdi Date: Tue, 7 Jun 2022 18:56:28 +0530 Subject: [PATCH 29/41] update p2.inf for traccar --- .../main/resources/conf/traccar-config.xml | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/traccar-config.xml diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/traccar-config.xml b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/traccar-config.xml new file mode 100644 index 00000000000..67de666e5e2 --- /dev/null +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/traccar-config.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + sample + http://localhost: + 8085 + 5055 + Authorization + Basic YWRtaW46YWRtaW4= + + + + From e88d5e9c3b1cfa138e9f47b6026e5ffe97404aea Mon Sep 17 00:00:00 2001 From: Rushdi Date: Thu, 9 Jun 2022 01:28:17 +0530 Subject: [PATCH 30/41] Add traccar configuration on p2.inf and updated mysql.sql --- .../api/service/addons/TraccarClientImpl.java | 19 +++++++----- .../main/resources/dbscripts/cdm/mysql.sql | 29 +++++++++++++++++++ .../src/main/resources/p2.inf | 1 + 3 files changed, 42 insertions(+), 7 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java index 53350753179..74fedd5dc78 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java @@ -158,13 +158,16 @@ public class TraccarClientImpl implements TraccarClient { String allUsers = fetchAllUsers(); //get all users JSONArray fetchAllUsers = new JSONArray(allUsers); //loop users for(int i=0; i Date: Thu, 9 Jun 2022 17:40:09 +0530 Subject: [PATCH 31/41] removed unwanted codes --- .../api/service/addons/TraccarClientImpl.java | 15 ++++----------- .../src/main/resources/conf/traccar-config.xml | 2 +- 2 files changed, 5 insertions(+), 12 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java index 74fedd5dc78..a4602bc3b01 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java @@ -421,14 +421,13 @@ public class TraccarClientImpl implements TraccarClient { authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), serverUrl(HttpReportingUtil.trackerServer()))); String result = res.get(); - log.info("---------res--------" + result); + 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); - log.info("DeviceId - " + deviceId); try { TrackerManagementDAOFactory.beginTransaction(); trackerDAO.addTrackerDevice(traccarDeviceId, deviceId, tenantId); @@ -486,6 +485,7 @@ public class TraccarClientImpl implements TraccarClient { addDevice(device, tenantId); }else{ //Update Location + log.info("Updating Location"); String method = TraccarHandlerConstants.Methods.GET; String url = locationUpdatePort+"/?id="+deviceInfo.getDeviceIdentifier()+ "×tamp="+deviceInfo.getTimestamp()+"&lat="+deviceInfo.getLat()+ @@ -494,7 +494,7 @@ public class TraccarClientImpl implements TraccarClient { executor.submit(new OkHttpClientThreadPool(url, null, method, authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), - serverUrl(HttpReportingUtil.trackerServer()))); + "http://localhost:")); //executor.shutdown(); } } @@ -515,9 +515,6 @@ public class TraccarClientImpl implements TraccarClient { log.info("------deviceId-----" + deviceId); log.info(trackerDeviceInfo); - log.info(new Gson().toJson(trackerDeviceInfo)); - log.info(trackerDeviceInfo.getDeviceId()); - log.info(trackerDeviceInfo.getTraccarDeviceId()); if(trackerDeviceInfo!=null){ //trackerDevice = new JSONObject(trackerDeviceInfo); int status = trackerDAO.removeTrackerDevice(deviceId, tenantId); @@ -540,11 +537,7 @@ public class TraccarClientImpl implements TraccarClient { TrackerManagementDAOFactory.closeConnection(); } - log.info("__________________"); - log.info(new Gson().toJson(trackerPermissionInfo)); - log.info(trackerPermissionInfo.get(0)); - log.info(new Gson().toJson(trackerPermissionInfo.get(0))); - log.info("__________________"); + log.info("--------Disenrolling Device--------"); //Delete from traccar if(trackerDeviceInfo!=null){ String method = TraccarHandlerConstants.Methods.DELETE; diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/traccar-config.xml b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/traccar-config.xml index 67de666e5e2..3521695b04e 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/traccar-config.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/traccar-config.xml @@ -27,7 +27,7 @@ sample http://localhost: - 8085 + 5055 Authorization Basic YWRtaW46YWRtaW4= From 120c1150ceac88e211ce1de848d8fe4d098ed03d Mon Sep 17 00:00:00 2001 From: Rushdi Date: Mon, 13 Jun 2022 12:14:22 +0530 Subject: [PATCH 32/41] fix traccar speed measure on kmh --- .../device/mgt/core/traccar/common/util/TraccarUtil.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/util/TraccarUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/util/TraccarUtil.java index 95aea15585c..6063d4d0c15 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/util/TraccarUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/util/TraccarUtil.java @@ -29,6 +29,8 @@ 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()); @@ -42,6 +44,7 @@ public class TraccarUtil { payload.put("deviceReadonly", traccarUser.getDeviceReadonly()); payload.put("readonly", traccarUser.getReadonly()); payload.put("expirationTime", traccarUser.getExpirationTime()); + payload.put("attributes", attribute); return payload; } From 29a2713af0985fbad930d93af6ff4c9ca676b9a4 Mon Sep 17 00:00:00 2001 From: Rushdi Date: Tue, 16 Aug 2022 10:26:58 +0530 Subject: [PATCH 33/41] update the traccar-config.xml on test --- .../src/test/resources/config/operation/traccar-config.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/operation/traccar-config.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/operation/traccar-config.xml index 67de666e5e2..3521695b04e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/operation/traccar-config.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/operation/traccar-config.xml @@ -27,7 +27,7 @@ sample http://localhost: - 8085 + 5055 Authorization Basic YWRtaW46YWRtaW4= From 31bb87db41b5c8a9b5405c5bc1be5623c338292e Mon Sep 17 00:00:00 2001 From: shamalka Date: Mon, 29 Aug 2022 17:07:49 +0530 Subject: [PATCH 34/41] Add missing error logs and fix formatting issues --- .../impl/DeviceManagementServiceImpl.java | 44 ++++++++----- .../core/dao/impl/tracker/TrackerDAOImpl.java | 62 +++++++++++++------ .../dao/util/TrackerManagementDAOUtil.java | 6 +- .../impl/DeviceInformationManagerImpl.java | 2 +- .../DeviceManagementProviderServiceImpl.java | 9 ++- .../impl/DeviceAPIClientServiceImpl.java | 1 + 6 files changed, 81 insertions(+), 43 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java index 9fea7b108c6..962373be34a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -132,7 +132,15 @@ import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import javax.validation.Valid; 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 java.sql.Timestamp; import java.text.ParseException; @@ -485,9 +493,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { String currentUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); JSONObject obj = new JSONObject(DeviceAPIClientServiceImpl.returnUser(currentUser)); - if(obj.has("error")){ + if (obj.has("error")) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(obj.getString("error")).build(); - }else{ + } else { int userId = obj.getInt("id"); List traccarValidIdList = new ArrayList<>(); /*Get Device Id List*/ @@ -504,8 +512,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { status.add("CREATED"); status.add("UNREACHABLE"); boolean isStatusEmpty = true; - for (String statusString : status){ - if (StringUtils.isNotBlank(statusString)){ + for (String statusString : status) { + if (StringUtils.isNotBlank(statusString)) { isStatusEmpty = false; break; } @@ -525,16 +533,15 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { if (result == null || result.getData() == null || result.getData().isEmpty()) { devices.setList(new ArrayList()); devices.setCount(0); - }else{ + } else { devices.setList((List) result.getData()); devices.setCount(result.getRecordsTotal()); } int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - for(int i=0; i getAllUserDevices = DeviceAPIClientServiceImpl.getUserIdofPermissionByUserIdNIdList(userId, traccarValidIdList); @@ -557,29 +563,35 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { getAllUserDevice.getTraccarDeviceId(), TraccarHandlerConstants.Types.REMOVE_TYPE_SINGLE); } - - } catch (JSONException e){ + } catch (JSONException e) { String msg = "not a JSONObject, "; log.error(msg); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } catch (DeviceManagementException e) { 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) { - log.error("ExecutionException : " + e); + String msg = "ExecutionException occured "; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } catch (InterruptedException e) { - log.error("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{ + } else { return Response.status(Response.Status.BAD_REQUEST).entity("Traccar is not enabled").build(); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/tracker/TrackerDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/tracker/TrackerDAOImpl.java index 0be2d2a7982..d98b630de33 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/tracker/TrackerDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/tracker/TrackerDAOImpl.java @@ -18,6 +18,8 @@ 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; @@ -36,6 +38,8 @@ 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 { @@ -51,7 +55,9 @@ public class TrackerDAOImpl implements TrackerDAO { return true; } catch (SQLException e) { - throw new TrackerManagementDAOException("Error occurred while adding on trackerDevice mapping table", 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); } @@ -74,6 +80,7 @@ public class TrackerDAOImpl implements TrackerDAO { 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); @@ -88,7 +95,7 @@ public class TrackerDAOImpl implements TrackerDAO { 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 = conn.prepareStatement(sql, new String[]{"id"}); stmt.setInt(1, deviceId); stmt.setInt(2, tenantId); stmt.executeUpdate(); @@ -98,7 +105,9 @@ public class TrackerDAOImpl implements TrackerDAO { } return status; } catch (SQLException e) { - throw new TrackerManagementDAOException("Error occurred while removing on trackerDevice table", e); + String msg = "Error occurred while removing on trackerDevice table"; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); } finally { TrackerManagementDAOUtil.cleanupResources(stmt, null); } @@ -122,7 +131,9 @@ public class TrackerDAOImpl implements TrackerDAO { } return trackerDeviceInfo; } catch (SQLException e) { - throw new TrackerManagementDAOException("Error occurred while retrieving data from the trackerDevice table ", 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); } @@ -132,7 +143,7 @@ public class TrackerDAOImpl implements TrackerDAO { public Boolean addTrackerGroup(int traccarGroupId, int groupId, int tenantId) throws TrackerManagementDAOException { PreparedStatement stmt = null; - int status = 1 ; + 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(?, ?, ?, ?)"; @@ -146,6 +157,7 @@ public class TrackerDAOImpl implements TrackerDAO { 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); @@ -169,6 +181,7 @@ public class TrackerDAOImpl implements TrackerDAO { 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); @@ -183,7 +196,7 @@ public class TrackerDAOImpl implements TrackerDAO { try { Connection conn = TrackerManagementDAOFactory.getConnection(); String sql = "DELETE FROM DM_EXT_GROUP_MAPPING WHERE ID = ? "; - stmt = conn.prepareStatement(sql, new String[] {"id"}); + stmt = conn.prepareStatement(sql, new String[]{"id"}); stmt.setInt(1, id); stmt.executeUpdate(); rs = stmt.getGeneratedKeys(); @@ -192,7 +205,9 @@ public class TrackerDAOImpl implements TrackerDAO { } return status; } catch (SQLException e) { - throw new TrackerManagementDAOException("Error occurred while removing from traccarGroup mapping table", 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); } @@ -216,7 +231,9 @@ public class TrackerDAOImpl implements TrackerDAO { } return trackerGroupInfo; } catch (SQLException e) { - throw new TrackerManagementDAOException("Error occurred while retrieving data from the traccarGroup mapping table ", 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); } @@ -236,7 +253,9 @@ public class TrackerDAOImpl implements TrackerDAO { return true; } catch (SQLException e) { - throw new TrackerManagementDAOException("Error occurred while adding permission on permissions mapping table", 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); } @@ -249,19 +268,20 @@ public class TrackerDAOImpl implements TrackerDAO { try { Connection conn = TrackerManagementDAOFactory.getConnection(); String sql = "DELETE FROM DM_EXT_PERMISSION_MAPPING WHERE TRACCAR_DEVICE_ID = ?"; - if(removeType != TraccarHandlerConstants.Types.REMOVE_TYPE_MULTIPLE){ + 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){ + if (removeType != TraccarHandlerConstants.Types.REMOVE_TYPE_MULTIPLE) { stmt.setInt(2, userId); } stmt.execute(); - return true; } catch (SQLException e) { - throw new TrackerManagementDAOException("Error occurred while removing permission from permissions mapping table", 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); } @@ -287,7 +307,9 @@ public class TrackerDAOImpl implements TrackerDAO { } return trackerPermissionInfo; } catch (SQLException e) { - throw new TrackerManagementDAOException("Error occurred while retrieving permissions data from permissions mapping table ", 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); } @@ -303,7 +325,7 @@ public class TrackerDAOImpl implements TrackerDAO { 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())){ + if (NotInDeviceIdList != null && (!NotInDeviceIdList.isEmpty())) { sql += TrackerManagementDAOUtil.buildDeviceIdNotInQuery(NotInDeviceIdList); } sql += " ORDER BY TRACCAR_USER_ID ASC"; @@ -311,8 +333,8 @@ public class TrackerDAOImpl implements TrackerDAO { stmt = conn.prepareStatement(sql); int paramIdx = 1; stmt.setInt(paramIdx++, userId); - if(NotInDeviceIdList!=null && (!NotInDeviceIdList.isEmpty())){ - for (int id : NotInDeviceIdList) { + if (NotInDeviceIdList != null && (!NotInDeviceIdList.isEmpty())) { + for (int id : NotInDeviceIdList) { stmt.setInt(paramIdx++, id); } } @@ -325,6 +347,7 @@ public class TrackerDAOImpl implements TrackerDAO { 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); @@ -335,7 +358,6 @@ public class TrackerDAOImpl implements TrackerDAO { public Boolean getUserIdofPermissionByDeviceIdNUserId(int deviceId, int userId) throws TrackerManagementDAOException { PreparedStatement stmt = null; ResultSet rs = null; - TrackerPermissionInfo trackerPermissionInfo = null; try { Connection conn = TrackerManagementDAOFactory.getConnection(); String sql = "SELECT TRACCAR_DEVICE_ID, TRACCAR_USER_ID FROM DM_EXT_PERMISSION_MAPPING WHERE " + @@ -347,7 +369,9 @@ public class TrackerDAOImpl implements TrackerDAO { rs = stmt.executeQuery(); return rs.next(); } catch (SQLException e) { - throw new TrackerManagementDAOException("Error occurred while retrieving permissions data from permissions mapping table ", 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); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/TrackerManagementDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/TrackerManagementDAOUtil.java index 117b994762c..fb06d34d012 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/TrackerManagementDAOUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/TrackerManagementDAOUtil.java @@ -95,7 +95,9 @@ public final class TrackerManagementDAOUtil { final InitialContext context = new InitialContext(jndiProperties); return (DataSource) context.lookup(dataSourceName); } catch (Exception e) { - throw new RuntimeException("Error in looking up data source: " + e.getMessage(), e); + String msg = "Error in looking up data source: " + e.getMessage(); + log.error(msg, e); + throw new RuntimeException(msg, e); } } @@ -129,11 +131,11 @@ public final class TrackerManagementDAOUtil { public static String buildDeviceIdNotInQuery(List 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(); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java index a5bc8b40969..553d1c3fa5c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java @@ -399,7 +399,7 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { log.error("InterruptedException : " + e); //throw new RuntimeException(e); } - }else{ + } else { log.info("location publishing is disabled and traccan disabled"); } //Tracker update GPS Location diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 53cab62fc0b..f4b991c7111 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -428,9 +428,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } 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 @@ -614,10 +616,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv String msg = "Error occurred while initiating transaction"; log.error(msg, e); throw new DeviceManagementException(msg, e); - } catch (Exception e) { - String msg = "Error occurred while dis-enrolling device: " + deviceId.getId(); - log.error(msg, e); - throw new DeviceManagementException(msg, e); } finally { DeviceManagementDAOFactory.closeConnection(); } @@ -3969,9 +3967,10 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv deviceLocation.setSpeed(Float.parseFloat(speed)); deviceLocation.setBearing(Float.parseFloat(bearing)); 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 // a warning for reference. + //Exception was not thrown due to being conflicted with non-traccar features log.warn("Error occurred while trying to add '" + device.getType() + "' device '" + device.getDeviceIdentifier() + "' (id:'" + device.getId() + "') location (lat:" + latitude + ", lon:" + longitude + ", altitude: " + altitude + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java index a8d4ee85ce5..9559ac262c6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java @@ -26,6 +26,7 @@ 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; From c312e69bf48d565a348cdc126643f66e4a55b44a Mon Sep 17 00:00:00 2001 From: shamalka Date: Mon, 29 Aug 2022 17:14:10 +0530 Subject: [PATCH 35/41] Revert unwanted change --- .../mgt/core/service/DeviceManagementProviderServiceImpl.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index f4b991c7111..784b8683d54 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -616,6 +616,10 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv String msg = "Error occurred while initiating transaction"; log.error(msg, e); throw new DeviceManagementException(msg, e); + } catch (Exception e) { + String msg = "Error occurred while dis-enrolling device: " + deviceId.getId(); + log.error(msg, e); + throw new DeviceManagementException(msg, e); } finally { DeviceManagementDAOFactory.closeConnection(); } From 642067b14642c43d9307e66618352821ec411ada Mon Sep 17 00:00:00 2001 From: shamalka Date: Mon, 29 Aug 2022 17:17:43 +0530 Subject: [PATCH 36/41] Remove wildcard imports --- .../DeviceManagementProviderServiceImpl.java | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 784b8683d54..c7f42afb463 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -51,8 +51,8 @@ import org.apache.http.protocol.HTTP; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.context.CarbonContext; 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; @@ -122,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.config.DeviceConfigurationManager; 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.device.details.mgt.DeviceDetailsMgtException; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; @@ -159,10 +166,9 @@ import java.sql.SQLException; import java.sql.Timestamp; import java.text.Format; import java.text.SimpleDateFormat; -import java.util.*; -import java.util.concurrent.TimeUnit; import java.util.ArrayList; import java.util.Calendar; +import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Enumeration; @@ -171,6 +177,7 @@ 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.ExecutionException; import java.util.stream.Collectors; From c68478dacab06bf56a3cd3af9f7add904e820f9c Mon Sep 17 00:00:00 2001 From: shamalka Date: Tue, 30 Aug 2022 09:10:20 +0530 Subject: [PATCH 37/41] Fix formatting issues --- .../jaxrs/service/impl/DeviceManagementServiceImpl.java | 9 --------- 1 file changed, 9 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java index 962373be34a..6cebe780269 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -544,11 +544,6 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { devices.getList().get(i).getId(), tenantId); int traccarDeviceId = trackerDevice.getTraccarDeviceId(); boolean getPermission = DeviceAPIClientServiceImpl.getUserIdofPermissionByDeviceIdNUserId(traccarDeviceId, userId); - log.info("--------------------"); - log.info(getPermission); - log.info(traccarDeviceId); - log.info(userId); - log.info("--------------------"); traccarValidIdList.add(traccarDeviceId); if (!getPermission) { DeviceAPIClientServiceImpl.addTrackerUserDevicePermission(userId, traccarDeviceId); @@ -563,10 +558,6 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { getAllUserDevice.getTraccarDeviceId(), TraccarHandlerConstants.Types.REMOVE_TYPE_SINGLE); } - } catch (JSONException e) { - String msg = "not a JSONObject, "; - log.error(msg); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } catch (DeviceManagementException e) { String msg = "Error occurred while fetching all enrolled devices"; log.error(msg, e); From ce0d0a1903fdc212faadf41ff9dc9559de2540c3 Mon Sep 17 00:00:00 2001 From: Rushdi Date: Wed, 31 Aug 2022 16:07:34 +0530 Subject: [PATCH 38/41] revert changes --- .../service/impl/DeviceManagementServiceImpl.java | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java index 6cebe780269..8fef89fd10e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -497,6 +497,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(obj.getString("error")).build(); } else { int userId = obj.getInt("id"); + String msg = ""; List traccarValidIdList = new ArrayList<>(); /*Get Device Id List*/ try { @@ -558,24 +559,28 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { getAllUserDevice.getTraccarDeviceId(), TraccarHandlerConstants.Types.REMOVE_TYPE_SINGLE); } + } catch (JSONException e) { + msg = "not a JSONObject. "; + log.error(msg); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } catch (DeviceManagementException e) { - String msg = "Error occurred while fetching all enrolled devices"; + 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"; + 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 ."; + 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 "; + msg = "ExecutionException occurred "; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } catch (InterruptedException e) { - String msg = "InterruptedException occured "; + msg = "InterruptedException occurred "; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } From df60140f9c40a2c115c2a119d9a51ae9b65eec7b Mon Sep 17 00:00:00 2001 From: Rushdi Date: Wed, 31 Aug 2022 20:38:33 +0530 Subject: [PATCH 39/41] Remove unwanted codelines and handle exceptions --- .../api/service/DeviceAPIClientService.java | 29 ++-- .../traccar/api/service/TraccarClient.java | 40 +++-- .../api/service/addons/TraccarClientImpl.java | 164 +++++++++--------- .../impl/DeviceAPIClientServiceImpl.java | 24 +-- .../config/TraccarConfigurationException.java | 38 ---- 5 files changed, 128 insertions(+), 167 deletions(-) delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/TraccarConfigurationException.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java index 28511f28685..605d4f7a46b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java @@ -23,8 +23,7 @@ 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 org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOException; import java.util.concurrent.ExecutionException; public interface DeviceAPIClientService { @@ -34,15 +33,16 @@ public interface DeviceAPIClientService { * * @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 + * @throws TrackerManagementDAOException errors thrown while inserting location of a traccar device */ - void updateLocation(Device device, DeviceLocation deviceLocation, int tenantId) throws ExecutionException, InterruptedException; + 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 + * @throws TrackerManagementDAOException errors thrown while creating a traccar device */ void addDevice(Device device, int tenantId) throws ExecutionException, InterruptedException; @@ -50,32 +50,35 @@ public interface DeviceAPIClientService { * Delete a device Traccar configuration records * * @param deviceId to be delete a device - * @throws TraccarConfigurationException errors thrown while deleting a device traccar configuration + * @throws TrackerManagementDAOException errors thrown while deleting a traccar device */ - void disEnrollDevice(int deviceId, int tenantId); + void disEnrollDevice(int deviceId, int tenantId) throws ExecutionException, InterruptedException; /** * Delete a device Traccar configuration records * * @param group to be add a group - * @throws TraccarConfigurationException errors thrown while adding a group traccar configuration + * @throws TrackerManagementDAOException errors thrown while adding a traccar group */ - void addGroup(DeviceGroup group, int groupID, int tenantId) throws TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException; + void addGroup(DeviceGroup group, int groupID, int tenantId) throws + TrackerManagementDAOException, 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 + * @throws TrackerManagementDAOException errors thrown while adding a traccar group */ - void updateGroup(DeviceGroup group, int groupID, int tenantId) throws ExecutionException, InterruptedException, TraccarConfigurationException, TrackerAlreadyExistException; + void updateGroup(DeviceGroup group, int groupID, int tenantId) throws + TrackerManagementDAOException, TrackerAlreadyExistException, ExecutionException, InterruptedException; /** * 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 + * @throws TrackerManagementDAOException errors thrown while adding a traccar group */ - void deleteGroup(int groupId, int tenantId) throws ExecutionException, InterruptedException, TraccarConfigurationException; + void deleteGroup(int groupId, int tenantId) throws + TrackerManagementDAOException, ExecutionException, InterruptedException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/TraccarClient.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/TraccarClient.java index c74db398ac6..e8beae1053e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/TraccarClient.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/TraccarClient.java @@ -27,7 +27,6 @@ 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; @@ -35,41 +34,46 @@ 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; + TrackerManagementDAOException, TrackerAlreadyExistException, ExecutionException, InterruptedException; void updateLocation(TraccarDevice device, TraccarPosition deviceInfo, int tenantId) throws - TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException, TrackerManagementDAOException; + TrackerManagementDAOException, TrackerAlreadyExistException, ExecutionException, InterruptedException; - void disEnrollDevice(int traccarDeviceId, int tenantId) throws TraccarConfigurationException; + void disEnrollDevice(int traccarDeviceId, int tenantId) throws + TrackerManagementDAOException, ExecutionException, InterruptedException; void addGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws - TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException; + TrackerManagementDAOException, TrackerAlreadyExistException, ExecutionException, InterruptedException; - void updateGroup(TraccarGroups groupInfo, int groupId, int tenantId) - throws TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException; + void updateGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws + TrackerManagementDAOException, TrackerAlreadyExistException, ExecutionException, InterruptedException; - void deleteGroup(int traccarGroupId, int tenantId) throws TraccarConfigurationException, ExecutionException, InterruptedException; + void deleteGroup(int traccarGroupId, int tenantId) throws + TrackerManagementDAOException, ExecutionException, InterruptedException; - void setPermission(int userId, int deviceId) throws TrackerManagementDAOException, ExecutionException, InterruptedException; + void setPermission(int userId, int deviceId) throws + TrackerManagementDAOException, ExecutionException, InterruptedException; - void removePermission(int userId, int deviceId, int removeType) throws ExecutionException, InterruptedException; + void removePermission(int userId, int deviceId, int removeType) throws + TrackerManagementDAOException, ExecutionException, InterruptedException; - List getUserIdofPermissionByUserIdNIdList(int userId, List NotInDeviceIdList) throws TrackerManagementDAOException; + List getUserIdofPermissionByUserIdNIdList(int userId, List NotInDeviceIdList) + throws TrackerManagementDAOException; - boolean getUserIdofPermissionByDeviceIdNUserId(int deviceId, int userId) throws TraccarConfigurationException, SQLException, TrackerManagementDAOException; + boolean getUserIdofPermissionByDeviceIdNUserId(int deviceId, int userId) throws + TrackerManagementDAOException, SQLException; - TrackerDeviceInfo getTrackerDevice(int deviceId, int tenantId) throws TraccarConfigurationException, SQLException, TrackerManagementDAOException; + TrackerDeviceInfo getTrackerDevice(int deviceId, int tenantId) throws + TrackerManagementDAOException, SQLException; - String fetchAllUsers() throws TraccarConfigurationException, ExecutionException, InterruptedException; + String fetchAllUsers() throws TrackerManagementDAOException, ExecutionException, InterruptedException; - String fetchUserInfo(String userName) throws TraccarConfigurationException, ExecutionException, InterruptedException; + String fetchUserInfo(String userName) throws TrackerManagementDAOException, 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; + String returnUser(String userName) throws TrackerManagementDAOException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java index a4602bc3b01..bbeab321c52 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java @@ -19,7 +19,6 @@ 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; @@ -47,7 +46,6 @@ 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; @@ -99,12 +97,6 @@ public class TraccarClientImpl implements TraccarClient { 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; @@ -150,7 +142,6 @@ public class TraccarClientImpl implements TraccarClient { authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), serverUrl(HttpReportingUtil.trackerServer()))); String res = result.get(); - //executor.shutdown(); return res; } @@ -239,8 +230,6 @@ public class TraccarClientImpl implements TraccarClient { authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), serverUrl(HttpReportingUtil.trackerServer()))); String result = res.get(); - //executor.shutdown(); - return result; } @@ -253,11 +242,11 @@ public class TraccarClientImpl implements TraccarClient { 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 { + public void setPermission(int userId, int deviceId) + throws ExecutionException, InterruptedException, TrackerManagementDAOException { JSONObject payload = new JSONObject(); payload.put("userId", userId); payload.put("deviceId", deviceId); @@ -269,31 +258,33 @@ public class TraccarClientImpl implements TraccarClient { authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), serverUrl(HttpReportingUtil.trackerServer()))); String result = res.get(); - //executor.shutdown(); + if(result==""){ + String msg = ""; try { TrackerManagementDAOFactory.beginTransaction(); trackerDAO.addTrackerUserDevicePermission(userId, deviceId); TrackerManagementDAOFactory.commitTransaction(); } catch (TrackerManagementDAOException e) { TrackerManagementDAOFactory.rollbackTransaction(); - String msg = "Error occurred while mapping with deviceId ."; + 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 ."; + 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); + log.error("Couldn't add the permission record: "+ result); } } - public void removePermission(int userId, int deviceId, int removeType) throws ExecutionException, InterruptedException { + public void removePermission(int userId, int deviceId, int removeType) + throws TrackerManagementDAOException, ExecutionException, InterruptedException { JSONObject payload = new JSONObject(); payload.put("userId", userId); payload.put("deviceId", deviceId); @@ -305,40 +296,42 @@ public class TraccarClientImpl implements TraccarClient { authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), serverUrl(HttpReportingUtil.trackerServer()))); String result = res.get(); - //executor.shutdown(); if(result!=null){ + String msg = ""; try { TrackerManagementDAOFactory.beginTransaction(); trackerDAO.removeTrackerUserDevicePermission(deviceId, userId, removeType); TrackerManagementDAOFactory.commitTransaction(); } catch (TrackerManagementDAOException e) { TrackerManagementDAOFactory.rollbackTransaction(); - String msg = "Error occurred while mapping with deviceId ."; + msg = "Error occurred while mapping with deviceId ."; log.error(msg, e); - //throw new TraccarConfigurationException(msg, e); + throw new TrackerManagementDAOException(msg, e); } catch (TransactionManagementException e) { TrackerManagementDAOFactory.rollbackTransaction(); - String msg = "Error occurred establishing the DB connection ."; + msg = "Error occurred establishing the DB connection ."; log.error(msg, e); - //throw new TraccarConfigurationException(msg, e); + throw new TrackerManagementDAOException(msg, e); } finally { TrackerManagementDAOFactory.closeConnection(); } } } - public List getUserIdofPermissionByUserIdNIdList(int userId, List NotInDeviceIdList) throws TrackerManagementDAOException { + public List getUserIdofPermissionByUserIdNIdList(int userId, List NotInDeviceIdList) + throws TrackerManagementDAOException { + String msg = ""; try { TrackerManagementDAOFactory.openConnection(); return trackerDAO.getUserIdofPermissionByUserIdNIdList(userId, NotInDeviceIdList); } catch (TrackerManagementDAOException e) { TrackerManagementDAOFactory.rollbackTransaction(); - String msg = "Error occurred while mapping with deviceId ."; + 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 ."; + msg = "Error occurred establishing the DB connection ."; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); } finally { @@ -347,15 +340,16 @@ public class TraccarClientImpl implements TraccarClient { } public TrackerDeviceInfo getTrackerDevice(int deviceId, int tenantId) throws TrackerManagementDAOException { + String msg = ""; try { TrackerManagementDAOFactory.openConnection(); return trackerDAO.getTrackerDevice(deviceId, tenantId); } catch (SQLException e) { - String msg = "Error occurred establishing the DB connection ."; + 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"; + msg="Could not add new device location"; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); } finally{ @@ -363,17 +357,19 @@ public class TraccarClientImpl implements TraccarClient { } } - public boolean getUserIdofPermissionByDeviceIdNUserId(int deviceId, int userId) throws TrackerManagementDAOException { + public boolean getUserIdofPermissionByDeviceIdNUserId(int deviceId, int userId) + throws TrackerManagementDAOException { Boolean result = false; + String msg = ""; try { TrackerManagementDAOFactory.openConnection(); result = trackerDAO.getUserIdofPermissionByDeviceIdNUserId(deviceId, userId); } catch (TrackerManagementDAOException e) { - String msg = "Error occurred while mapping with deviceId ."; + 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 ."; + msg = "Error occurred establishing the DB connection ."; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); } finally { @@ -386,25 +382,26 @@ public class TraccarClientImpl implements TraccarClient { * 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 + * @throws TrackerManagementDAOException Failed while add Traccar Device the operation */ public void addDevice(TraccarDevice traccarDevice, int tenantId) throws - TrackerAlreadyExistException, ExecutionException, InterruptedException, TrackerManagementDAOException { + TrackerManagementDAOException, TrackerAlreadyExistException, ExecutionException, InterruptedException { TrackerDeviceInfo trackerDeviceInfo = null; + String msg = ""; try { TrackerManagementDAOFactory.openConnection(); trackerDeviceInfo = trackerDAO.getTrackerDevice(traccarDevice.getId(), tenantId); if(trackerDeviceInfo!=null){ - String msg = "The device already exist"; + msg = "The device already exist"; log.error(msg); - //throw new TrackerAlreadyExistException(msg); + throw new TrackerAlreadyExistException(msg); } } catch (TrackerManagementDAOException e) { - String msg = "Error occurred while mapping with deviceId ."; + 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 ."; + msg = "Error occurred establishing the DB connection ."; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); } finally { @@ -421,7 +418,6 @@ public class TraccarClientImpl implements TraccarClient { 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")){ @@ -438,12 +434,12 @@ public class TraccarClientImpl implements TraccarClient { TrackerManagementDAOFactory.commitTransaction(); } catch (TrackerManagementDAOException e) { TrackerManagementDAOFactory.rollbackTransaction(); - String msg = "Error occurred while mapping with deviceId ."; + 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 ."; + msg = "Error occurred establishing the DB connection ."; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); } finally { @@ -455,24 +451,25 @@ public class TraccarClientImpl implements TraccarClient { } } } - //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 { + public void updateLocation(TraccarDevice device, TraccarPosition deviceInfo, int tenantId) throws + TrackerManagementDAOException, TrackerAlreadyExistException, ExecutionException, InterruptedException { TrackerDeviceInfo trackerDeviceInfo = null; + String msg = ""; try { TrackerManagementDAOFactory.openConnection(); trackerDeviceInfo = trackerDAO.getTrackerDevice(device.getId(), tenantId); } catch (SQLException e) { - String msg = "Error occurred establishing the DB connection ."; + 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"; + msg = "Could not add new device location"; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); } finally{ @@ -495,28 +492,25 @@ public class TraccarClientImpl implements TraccarClient { 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 + * @throws TrackerManagementDAOException Failed while dis-enroll a Traccar Device operation */ - public void disEnrollDevice(int deviceId, int tenantId) throws TraccarConfigurationException { + public void disEnrollDevice(int deviceId, int tenantId) throws TrackerManagementDAOException, ExecutionException, InterruptedException { TrackerDeviceInfo trackerDeviceInfo = null; List trackerPermissionInfo = null; - //JSONObject trackerDevice = null; + String msg = ""; try { TrackerManagementDAOFactory.beginTransaction(); trackerDeviceInfo = trackerDAO.getTrackerDevice(deviceId, tenantId); - log.info("------deviceId-----" + deviceId); - log.info(trackerDeviceInfo); + log.info("deviceId - " + deviceId); if(trackerDeviceInfo!=null){ - //trackerDevice = new JSONObject(trackerDeviceInfo); int status = trackerDAO.removeTrackerDevice(deviceId, tenantId); log.info("Status" + status); TrackerManagementDAOFactory.commitTransaction(); @@ -525,14 +519,14 @@ public class TraccarClientImpl implements TraccarClient { } } catch (TransactionManagementException e) { TrackerManagementDAOFactory.rollbackTransaction(); - String msg = "Error occurred establishing the DB connection"; + msg = "Error occurred establishing the DB connection"; log.error(msg, e); - throw new TraccarConfigurationException(msg, e); + throw new TrackerManagementDAOException(msg, e); } catch (TrackerManagementDAOException e) { TrackerManagementDAOFactory.rollbackTransaction(); - String msg = "Error occurred while mapping with deviceId"; + msg = "Error occurred while mapping with deviceId"; log.error(msg, e); - throw new TraccarConfigurationException(msg, e); + throw new TrackerManagementDAOException(msg, e); } finally { TrackerManagementDAOFactory.closeConnection(); } @@ -546,7 +540,6 @@ public class TraccarClientImpl implements TraccarClient { executor.submit(new OkHttpClientThreadPool(url, null, method, authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), serverUrl(HttpReportingUtil.trackerServer()))); - //executor.shutdown(); //remove permissions try { @@ -556,10 +549,7 @@ public class TraccarClientImpl implements TraccarClient { 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); + throw new ExecutionException(e); } } } @@ -567,27 +557,28 @@ public class TraccarClientImpl implements TraccarClient { /** * Add Traccar Device operation. * @param groupInfo with groupName - * @throws TraccarConfigurationException Failed while add Traccar Device the operation + * @throws TrackerManagementDAOException Failed while add Traccar Device the operation */ public void addGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws - TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException { + TrackerManagementDAOException, TrackerAlreadyExistException, ExecutionException, InterruptedException { TrackerGroupInfo trackerGroupInfo = null; + String msg = ""; try { TrackerManagementDAOFactory.openConnection(); trackerGroupInfo = trackerDAO.getTrackerGroup(groupId, tenantId); if (trackerGroupInfo!=null){ - String msg = "The group already exit"; + msg = "The group already exit"; log.error(msg); throw new TrackerAlreadyExistException(msg); } } catch (TrackerManagementDAOException e) { - String msg = "Error occurred while mapping with groupId."; + msg = "Error occurred while mapping with groupId."; log.error(msg, e); - throw new TraccarConfigurationException(msg, e); + throw new TrackerManagementDAOException(msg, e); } catch (SQLException e) { - String msg = "Error occurred establishing the DB connection."; + msg = "Error occurred establishing the DB connection."; log.error(msg, e); - throw new TraccarConfigurationException(msg, e); + throw new TrackerManagementDAOException(msg, e); } finally { TrackerManagementDAOFactory.closeConnection(); } @@ -617,15 +608,15 @@ public class TraccarClientImpl implements TraccarClient { trackerDAO.updateTrackerGroupIdANDStatus(trackerGroupInfo.getTraccarGroupId(), groupId, tenantId, 1); } } catch (TrackerManagementDAOException e) { - String msg = "Error occurred while mapping with deviceId ."; + msg = "Error occurred while mapping with deviceId. "; log.error(msg, e); TrackerManagementDAOFactory.rollbackTransaction(); - throw new TraccarConfigurationException(msg, e); + throw new TrackerManagementDAOException(msg, e); } catch (TransactionManagementException e) { - String msg = "Error occurred establishing the DB connection ."; + msg = "Error occurred establishing the DB connection. "; log.error(msg, e); TrackerManagementDAOFactory.rollbackTransaction(); - throw new TraccarConfigurationException(msg, e); + throw new TrackerManagementDAOException(msg, e); } finally { TrackerManagementDAOFactory.closeConnection(); } @@ -635,25 +626,25 @@ public class TraccarClientImpl implements TraccarClient { }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 + * @throws TrackerManagementDAOException Failed while add Traccar Device the operation */ public void updateGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws - TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException { + TrackerManagementDAOException, TrackerAlreadyExistException, ExecutionException, InterruptedException { TrackerGroupInfo res = null; + String msg = ""; try { TrackerManagementDAOFactory.openConnection(); res = trackerDAO.getTrackerGroup(groupId, tenantId); } catch (SQLException e) { - String msg = "Error occurred establishing the DB connection ."; + msg = "Error occurred establishing the DB connection. "; log.error(msg, e); } catch (TrackerManagementDAOException e) { - String msg="Could not find traccar group details"; + msg="Could not find traccar group details. "; log.error(msg, e); } finally{ TrackerManagementDAOFactory.closeConnection(); @@ -670,14 +661,14 @@ public class TraccarClientImpl implements TraccarClient { TrackerManagementDAOFactory.commitTransaction(); } catch (TrackerManagementDAOException e) { TrackerManagementDAOFactory.rollbackTransaction(); - String msg="Could not update the traccar group"; + msg="Could not update the traccar group. "; log.error(msg, e); - throw new TraccarConfigurationException(msg, e); + throw new TrackerManagementDAOException(msg, e); } catch (TransactionManagementException e) { TrackerManagementDAOFactory.rollbackTransaction(); - String msg = "Error occurred establishing the DB connection ."; + msg = "Error occurred establishing the DB connection. "; log.error(msg, e); - throw new TraccarConfigurationException(msg, e); + throw new TrackerManagementDAOException(msg, e); } finally{ TrackerManagementDAOFactory.closeConnection(); } @@ -694,18 +685,18 @@ public class TraccarClientImpl implements TraccarClient { 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 + * @throws TrackerManagementDAOException Failed while add Traccar Device the operation */ - public void deleteGroup(int groupId, int tenantId) throws TraccarConfigurationException, ExecutionException, InterruptedException { + public void deleteGroup(int groupId, int tenantId) throws TrackerManagementDAOException, ExecutionException, InterruptedException { TrackerGroupInfo res = null; JSONObject obj = null; + String msg = ""; try { TrackerManagementDAOFactory.beginTransaction(); res = trackerDAO.getTrackerGroup(groupId, tenantId); @@ -721,17 +712,18 @@ public class TraccarClientImpl implements TraccarClient { 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"; + msg = "Error occurred establishing the DB connection. "; log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); } catch (TrackerManagementDAOException e) { TrackerManagementDAOFactory.rollbackTransaction(); - String msg = "Error occurred while mapping with groupId"; + msg = "Error occurred while mapping with groupId. "; log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); } finally { TrackerManagementDAOFactory.closeConnection(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java index 9559ac262c6..540dcfb8df1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java @@ -26,7 +26,6 @@ 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; @@ -36,7 +35,6 @@ 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; @@ -85,31 +83,32 @@ public class DeviceAPIClientServiceImpl implements DeviceAPIClientService { } } - public void disEnrollDevice(int deviceId, int tenantId) { + public void disEnrollDevice(int deviceId, int tenantId) throws ExecutionException, InterruptedException{ TraccarClientImpl client = new TraccarClientImpl(); try { client.disEnrollDevice(deviceId, tenantId); - } catch (TraccarConfigurationException e) { + } catch (TrackerManagementDAOException 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 { + TrackerManagementDAOException, 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 { + public void updateGroup(DeviceGroup group, int groupId, int tenantId) throws + TrackerManagementDAOException, 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 { + TrackerManagementDAOException, ExecutionException, InterruptedException { TraccarClientImpl client = new TraccarClientImpl(); client.deleteGroup(groupId, tenantId); } @@ -131,14 +130,13 @@ public class DeviceAPIClientServiceImpl implements DeviceAPIClientService { return client.getUserIdofPermissionByDeviceIdNUserId(deviceId, userId); } - public static String createUser(TraccarUser traccarUser) throws - TrackerManagementDAOException, ExecutionException, InterruptedException { + public static String createUser(TraccarUser traccarUser) throws ExecutionException, InterruptedException { TraccarClientImpl client = new TraccarClientImpl(); return client.createUser(traccarUser); } public static String updateUser(TraccarUser traccarUser, int userId) throws - TrackerManagementDAOException, ExecutionException, InterruptedException { + ExecutionException, InterruptedException { TraccarClientImpl client = new TraccarClientImpl(); return client.updateUser(traccarUser, userId); } @@ -161,12 +159,14 @@ public class DeviceAPIClientServiceImpl implements DeviceAPIClientService { client.setPermission(userId, deviceId); } - public static void removeTrackerUserDevicePermission(int userId, int deviceId, int removeType) throws TrackerManagementDAOException, ExecutionException, InterruptedException { + 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 getUserIdofPermissionByUserIdNIdList(int userId, List NotInDeviceIdList) throws TrackerManagementDAOException { + public static List getUserIdofPermissionByUserIdNIdList(int userId, List NotInDeviceIdList) throws + TrackerManagementDAOException { TraccarClientImpl client = new TraccarClientImpl(); return client.getUserIdofPermissionByUserIdNIdList(userId, NotInDeviceIdList); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/TraccarConfigurationException.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/TraccarConfigurationException.java deleted file mode 100644 index ba601140411..00000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/TraccarConfigurationException.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * 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); - } -} From d61814329c748d269cb408d0bed2852cb747de38 Mon Sep 17 00:00:00 2001 From: shamalka Date: Thu, 1 Sep 2022 11:03:45 +0530 Subject: [PATCH 40/41] Revert global exception msg --- .../impl/DeviceManagementServiceImpl.java | 13 +- .../api/service/addons/TraccarClientImpl.java | 235 +++++++++--------- 2 files changed, 120 insertions(+), 128 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java index 8fef89fd10e..6600a20c1ba 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -497,7 +497,6 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(obj.getString("error")).build(); } else { int userId = obj.getInt("id"); - String msg = ""; List traccarValidIdList = new ArrayList<>(); /*Get Device Id List*/ try { @@ -560,27 +559,27 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { TraccarHandlerConstants.Types.REMOVE_TYPE_SINGLE); } } catch (JSONException e) { - msg = "not a JSONObject. "; + String msg = "not a JSONObject. "; log.error(msg); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } catch (DeviceManagementException e) { - msg = "Error occurred while fetching all enrolled devices. "; + 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) { - msg = "Error occurred while checking device access authorization. "; + 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) { - msg = "Error occurred while mapping with deviceId ."; + 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) { - msg = "ExecutionException occurred "; + String msg = "ExecutionException occurred "; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } catch (InterruptedException e) { - msg = "InterruptedException occurred "; + String msg = "InterruptedException occurred "; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java index bbeab321c52..016e083bf95 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java @@ -85,7 +85,7 @@ public class TraccarClientImpl implements TraccarClient { .connectTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) .readTimeout(45, TimeUnit.SECONDS) - .connectionPool(new ConnectionPool(100,50,TimeUnit.SECONDS)) + .connectionPool(new ConnectionPool(100, 50, TimeUnit.SECONDS)) .build(); this.trackerDAO = TrackerManagementDAOFactory.getTrackerDAO(); } @@ -113,30 +113,30 @@ public class TraccarClientImpl implements TraccarClient { Request request; Response response; - if(Objects.equals(method, TraccarHandlerConstants.Methods.POST)){ + 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)){ + } 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){ + } 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{ + } else { builder = builder.delete(); } } - request = builder.url(serverUri+publisherUrlWithContext).addHeader(authorization, authorizeKey).build(); + 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"; + String url = defaultPort + "/api/users"; Future result = executor.submit(new OkHttpClientThreadPool(url, null, method, authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), @@ -148,15 +148,15 @@ public class TraccarClientImpl implements TraccarClient { 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 res = executor.submit(new OkHttpClientThreadPool(url, payload, method, @@ -235,7 +235,7 @@ public class TraccarClientImpl implements TraccarClient { public String updateUser(TraccarUser traccarUser, int userId) throws ExecutionException, InterruptedException { String method = TraccarHandlerConstants.Methods.PUT; - String url = defaultPort+"/api/users/"+userId; + String url = defaultPort + "/api/users/" + userId; JSONObject payload = TraccarUtil.TraccarUserPayload(traccarUser); Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method, @@ -252,34 +252,33 @@ public class TraccarClientImpl implements TraccarClient { payload.put("deviceId", deviceId); String method = TraccarHandlerConstants.Methods.POST; - String url = defaultPort+"/api/permissions"; + String url = defaultPort + "/api/permissions"; Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method, authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), serverUrl(HttpReportingUtil.trackerServer()))); String result = res.get(); - if(result==""){ - String msg = ""; + if (result.equals("")) { try { TrackerManagementDAOFactory.beginTransaction(); trackerDAO.addTrackerUserDevicePermission(userId, deviceId); TrackerManagementDAOFactory.commitTransaction(); } catch (TrackerManagementDAOException e) { TrackerManagementDAOFactory.rollbackTransaction(); - msg = "Error occurred while mapping with deviceId ."; + String msg = "Error occurred while mapping with deviceId ."; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); } catch (TransactionManagementException e) { TrackerManagementDAOFactory.rollbackTransaction(); - msg = "Error occurred establishing the DB connection ."; + String msg = "Error occurred establishing the DB connection ."; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); } finally { TrackerManagementDAOFactory.closeConnection(); } - }else{ - log.error("Couldn't add the permission record: "+ result); + } else { + log.error("Couldn't add the permission record: " + result); } } @@ -290,27 +289,26 @@ public class TraccarClientImpl implements TraccarClient { payload.put("deviceId", deviceId); String method = TraccarHandlerConstants.Methods.DELETE; - String url = defaultPort+"/api/permissions"; + String url = defaultPort + "/api/permissions"; Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method, authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), serverUrl(HttpReportingUtil.trackerServer()))); String result = res.get(); - if(result!=null){ - String msg = ""; + if (result != null) { try { TrackerManagementDAOFactory.beginTransaction(); trackerDAO.removeTrackerUserDevicePermission(deviceId, userId, removeType); TrackerManagementDAOFactory.commitTransaction(); } catch (TrackerManagementDAOException e) { TrackerManagementDAOFactory.rollbackTransaction(); - msg = "Error occurred while mapping with deviceId ."; + String msg = "Error occurred while mapping with deviceId ."; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); } catch (TransactionManagementException e) { TrackerManagementDAOFactory.rollbackTransaction(); - msg = "Error occurred establishing the DB connection ."; + String msg = "Error occurred establishing the DB connection ."; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); } finally { @@ -321,17 +319,16 @@ public class TraccarClientImpl implements TraccarClient { public List getUserIdofPermissionByUserIdNIdList(int userId, List NotInDeviceIdList) throws TrackerManagementDAOException { - String msg = ""; try { TrackerManagementDAOFactory.openConnection(); return trackerDAO.getUserIdofPermissionByUserIdNIdList(userId, NotInDeviceIdList); } catch (TrackerManagementDAOException e) { TrackerManagementDAOFactory.rollbackTransaction(); - msg = "Error occurred while mapping with deviceId ."; + String msg = "Error occurred while mapping with deviceId ."; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); } catch (SQLException e) { - msg = "Error occurred establishing the DB connection ."; + String msg = "Error occurred establishing the DB connection ."; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); } finally { @@ -340,19 +337,18 @@ public class TraccarClientImpl implements TraccarClient { } public TrackerDeviceInfo getTrackerDevice(int deviceId, int tenantId) throws TrackerManagementDAOException { - String msg = ""; try { TrackerManagementDAOFactory.openConnection(); return trackerDAO.getTrackerDevice(deviceId, tenantId); } catch (SQLException e) { - msg = "Error occurred establishing the DB connection ."; + String msg = "Error occurred establishing the DB connection ."; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); } catch (TrackerManagementDAOException e) { - msg="Could not add new device location"; + String msg = "Could not add new device location"; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); - } finally{ + } finally { TrackerManagementDAOFactory.closeConnection(); } } @@ -360,16 +356,15 @@ public class TraccarClientImpl implements TraccarClient { public boolean getUserIdofPermissionByDeviceIdNUserId(int deviceId, int userId) throws TrackerManagementDAOException { Boolean result = false; - String msg = ""; try { TrackerManagementDAOFactory.openConnection(); result = trackerDAO.getUserIdofPermissionByDeviceIdNUserId(deviceId, userId); } catch (TrackerManagementDAOException e) { - msg = "Error occurred while mapping with deviceId ."; + String msg = "Error occurred while mapping with deviceId ."; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); } catch (SQLException e) { - msg = "Error occurred establishing the DB connection ."; + String msg = "Error occurred establishing the DB connection ."; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); } finally { @@ -380,47 +375,47 @@ public class TraccarClientImpl implements TraccarClient { /** * Add Traccar Device operation. - * @param traccarDevice with DeviceName UniqueId, Status, Disabled LastUpdate, PositionId, GroupId - * Model, Contact, Category, fenceIds + * + * @param traccarDevice with DeviceName UniqueId, Status, Disabled LastUpdate, PositionId, GroupId + * Model, Contact, Category, fenceIds * @throws TrackerManagementDAOException Failed while add Traccar Device the operation */ public void addDevice(TraccarDevice traccarDevice, int tenantId) throws TrackerManagementDAOException, TrackerAlreadyExistException, ExecutionException, InterruptedException { TrackerDeviceInfo trackerDeviceInfo = null; - String msg = ""; try { TrackerManagementDAOFactory.openConnection(); trackerDeviceInfo = trackerDAO.getTrackerDevice(traccarDevice.getId(), tenantId); - if(trackerDeviceInfo!=null){ - msg = "The device already exist"; + if (trackerDeviceInfo != null) { + String msg = "The device already exist"; log.error(msg); throw new TrackerAlreadyExistException(msg); } } catch (TrackerManagementDAOException e) { - msg = "Error occurred while mapping with deviceId ."; + String msg = "Error occurred while mapping with deviceId ."; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); } catch (SQLException e) { - msg = "Error occurred establishing the DB connection ."; + String msg = "Error occurred establishing the DB connection ."; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); } finally { TrackerManagementDAOFactory.closeConnection(); } - if(trackerDeviceInfo==null){ + if (trackerDeviceInfo == null) { //add the device String method = TraccarHandlerConstants.Methods.POST; - String url = defaultPort+"/api/devices"; + String url = defaultPort + "/api/devices"; JSONObject payload = TraccarUtil.TraccarDevicePayload(traccarDevice); Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method, authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), serverUrl(HttpReportingUtil.trackerServer()))); String result = res.get(); - if(result.charAt(0)=='{'){ + if (result.charAt(0) == '{') { JSONObject obj = new JSONObject(result); - if (obj.has("id")){ + if (obj.has("id")) { int traccarDeviceId = obj.getInt("id"); int deviceId = traccarDevice.getId(); log.info("TraccarDeviceId - " + traccarDeviceId); @@ -428,18 +423,18 @@ public class TraccarClientImpl implements TraccarClient { TrackerManagementDAOFactory.beginTransaction(); trackerDAO.addTrackerDevice(traccarDeviceId, deviceId, tenantId); trackerDeviceInfo = trackerDAO.getTrackerDevice(deviceId, tenantId); - if(trackerDeviceInfo.getStatus()==0){ + if (trackerDeviceInfo.getStatus() == 0) { trackerDAO.updateTrackerDeviceIdANDStatus(trackerDeviceInfo.getTraccarDeviceId(), deviceId, tenantId, 1); } TrackerManagementDAOFactory.commitTransaction(); } catch (TrackerManagementDAOException e) { TrackerManagementDAOFactory.rollbackTransaction(); - msg = "Error occurred while mapping with deviceId ."; + String msg = "Error occurred while mapping with deviceId ."; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); } catch (TransactionManagementException e) { TrackerManagementDAOFactory.rollbackTransaction(); - msg = "Error occurred establishing the DB connection ."; + String msg = "Error occurred establishing the DB connection ."; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); } finally { @@ -455,39 +450,39 @@ public class TraccarClientImpl implements TraccarClient { /** * Add Device GPS Location operation. - * @param deviceInfo with DeviceIdentifier, Timestamp, Lat, Lon, Bearing, Speed, ignition + * + * @param deviceInfo with DeviceIdentifier, Timestamp, Lat, Lon, Bearing, Speed, ignition */ public void updateLocation(TraccarDevice device, TraccarPosition deviceInfo, int tenantId) throws TrackerManagementDAOException, TrackerAlreadyExistException, ExecutionException, InterruptedException { TrackerDeviceInfo trackerDeviceInfo = null; - String msg = ""; try { TrackerManagementDAOFactory.openConnection(); trackerDeviceInfo = trackerDAO.getTrackerDevice(device.getId(), tenantId); } catch (SQLException e) { - msg = "Error occurred establishing the DB connection ."; + String msg = "Error occurred establishing the DB connection ."; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); } catch (TrackerManagementDAOException e) { - msg = "Could not add new device location"; + String msg = "Could not add new device location"; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); - } finally{ + } finally { TrackerManagementDAOFactory.closeConnection(); } //check if the device is already exist before updating the location - if (trackerDeviceInfo == null){ + if (trackerDeviceInfo == null) { //add device if not exist addDevice(device, tenantId); - }else{ + } else { //Update Location log.info("Updating Location"); String method = TraccarHandlerConstants.Methods.GET; - String url = locationUpdatePort+"/?id="+deviceInfo.getDeviceIdentifier()+ - "×tamp="+deviceInfo.getTimestamp()+"&lat="+deviceInfo.getLat()+ - "&lon="+deviceInfo.getLon()+"&bearing="+deviceInfo.getBearing()+ - "&speed="+deviceInfo.getSpeed()+"&ignition=true"; + String url = locationUpdatePort + "/?id=" + deviceInfo.getDeviceIdentifier() + + "×tamp=" + 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()), @@ -497,20 +492,19 @@ public class TraccarClientImpl implements TraccarClient { /** * Dis-enroll a Device operation. - * @param deviceId identified via deviceIdentifier + * + * @param deviceId identified via deviceIdentifier * @throws TrackerManagementDAOException Failed while dis-enroll a Traccar Device operation */ public void disEnrollDevice(int deviceId, int tenantId) throws TrackerManagementDAOException, ExecutionException, InterruptedException { TrackerDeviceInfo trackerDeviceInfo = null; List trackerPermissionInfo = null; - String msg = ""; - try { TrackerManagementDAOFactory.beginTransaction(); trackerDeviceInfo = trackerDAO.getTrackerDevice(deviceId, tenantId); log.info("deviceId - " + deviceId); - if(trackerDeviceInfo!=null){ + if (trackerDeviceInfo != null) { int status = trackerDAO.removeTrackerDevice(deviceId, tenantId); log.info("Status" + status); TrackerManagementDAOFactory.commitTransaction(); @@ -519,23 +513,22 @@ public class TraccarClientImpl implements TraccarClient { } } catch (TransactionManagementException e) { TrackerManagementDAOFactory.rollbackTransaction(); - msg = "Error occurred establishing the DB connection"; + String msg = "Error occurred establishing the DB connection"; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); } catch (TrackerManagementDAOException e) { TrackerManagementDAOFactory.rollbackTransaction(); - msg = "Error occurred while mapping with deviceId"; + String msg = "Error occurred while mapping with deviceId"; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); } finally { TrackerManagementDAOFactory.closeConnection(); } - log.info("--------Disenrolling Device--------"); //Delete from traccar - if(trackerDeviceInfo!=null){ + if (trackerDeviceInfo != null) { String method = TraccarHandlerConstants.Methods.DELETE; - String url = defaultPort+"/api/devices/"+trackerPermissionInfo.get(0).getTraccarDeviceId(); + String url = defaultPort + "/api/devices/" + trackerPermissionInfo.get(0).getTraccarDeviceId(); executor.submit(new OkHttpClientThreadPool(url, null, method, authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), @@ -556,27 +549,27 @@ public class TraccarClientImpl implements TraccarClient { /** * Add Traccar Device operation. - * @param groupInfo with groupName + * + * @param groupInfo with groupName * @throws TrackerManagementDAOException Failed while add Traccar Device the operation */ public void addGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws TrackerManagementDAOException, TrackerAlreadyExistException, ExecutionException, InterruptedException { TrackerGroupInfo trackerGroupInfo = null; - String msg = ""; try { TrackerManagementDAOFactory.openConnection(); trackerGroupInfo = trackerDAO.getTrackerGroup(groupId, tenantId); - if (trackerGroupInfo!=null){ - msg = "The group already exit"; + if (trackerGroupInfo != null) { + String msg = "The group already exit"; log.error(msg); throw new TrackerAlreadyExistException(msg); } } catch (TrackerManagementDAOException e) { - msg = "Error occurred while mapping with groupId."; + String msg = "Error occurred while mapping with groupId."; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); } catch (SQLException e) { - msg = "Error occurred establishing the DB connection."; + String msg = "Error occurred establishing the DB connection."; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); } finally { @@ -588,72 +581,72 @@ public class TraccarClientImpl implements TraccarClient { payload.put("attributes", new JSONObject()); String method = TraccarHandlerConstants.Methods.POST; - String url = defaultPort+"/api/groups"; + String url = defaultPort + "/api/groups"; Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method, authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), serverUrl(HttpReportingUtil.trackerServer()))); String result = res.get(); - if(result.charAt(0)=='{'){ + if (result.charAt(0) == '{') { JSONObject obj = new JSONObject(result); - if (obj.has("id")){ + 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){ + if (trackerGroupInfo.getStatus() == 0) { trackerDAO.updateTrackerGroupIdANDStatus(trackerGroupInfo.getTraccarGroupId(), groupId, tenantId, 1); } } catch (TrackerManagementDAOException e) { - msg = "Error occurred while mapping with deviceId. "; + String msg = "Error occurred while mapping with deviceId. "; log.error(msg, e); TrackerManagementDAOFactory.rollbackTransaction(); throw new TrackerManagementDAOException(msg, e); } catch (TransactionManagementException e) { - msg = "Error occurred establishing the DB connection. "; + String msg = "Error occurred establishing the DB connection. "; log.error(msg, e); TrackerManagementDAOFactory.rollbackTransaction(); throw new TrackerManagementDAOException(msg, e); } finally { TrackerManagementDAOFactory.closeConnection(); } - }else{ + } else { log.error("Something went wrong_1: " + result); } - }else{ + } else { log.error("Something went wrong_2: " + result); } } /** * update Traccar Group operation. - * @param groupInfo with groupName + * + * @param groupInfo with groupName * @throws TrackerManagementDAOException Failed while add Traccar Device the operation */ public void updateGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws TrackerManagementDAOException, TrackerAlreadyExistException, ExecutionException, InterruptedException { TrackerGroupInfo res = null; - String msg = ""; try { TrackerManagementDAOFactory.openConnection(); res = trackerDAO.getTrackerGroup(groupId, tenantId); } catch (SQLException e) { - msg = "Error occurred establishing the DB connection. "; + String msg = "Error occurred establishing the DB connection. "; log.error(msg, e); } catch (TrackerManagementDAOException e) { - msg="Could not find traccar group details. "; + String msg = "Could not find traccar group details. "; log.error(msg, e); - } finally{ + } finally { TrackerManagementDAOFactory.closeConnection(); } - if ((res==null) || (res.getTraccarGroupId()==0)){ + 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)){ + } else if (res != null && (res.getTraccarGroupId() != 0 && res.getStatus() == 0)) { //update the traccargroupId and status try { TrackerManagementDAOFactory.beginTransaction(); @@ -661,18 +654,18 @@ public class TraccarClientImpl implements TraccarClient { TrackerManagementDAOFactory.commitTransaction(); } catch (TrackerManagementDAOException e) { TrackerManagementDAOFactory.rollbackTransaction(); - msg="Could not update the traccar group. "; + String msg = "Could not update the traccar group. "; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); } catch (TransactionManagementException e) { TrackerManagementDAOFactory.rollbackTransaction(); - msg = "Error occurred establishing the DB connection. "; + String msg = "Error occurred establishing the DB connection. "; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); - } finally{ + } finally { TrackerManagementDAOFactory.closeConnection(); } - }else{ + } else { JSONObject obj = new JSONObject(res); JSONObject payload = new JSONObject(); payload.put("id", obj.getInt("traccarGroupId")); @@ -680,7 +673,7 @@ public class TraccarClientImpl implements TraccarClient { payload.put("attributes", new JSONObject()); String method = TraccarHandlerConstants.Methods.PUT; - String url = defaultPort+"/api/groups/"+obj.getInt("traccarGroupId"); + String url = defaultPort + "/api/groups/" + obj.getInt("traccarGroupId"); executor.submit(new OkHttpClientThreadPool(url, payload, method, authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), @@ -690,24 +683,24 @@ public class TraccarClientImpl implements TraccarClient { /** * Add Traccar Device operation. + * * @param groupId * @throws TrackerManagementDAOException Failed while add Traccar Device the operation */ public void deleteGroup(int groupId, int tenantId) throws TrackerManagementDAOException, ExecutionException, InterruptedException { TrackerGroupInfo res = null; JSONObject obj = null; - String msg = ""; try { TrackerManagementDAOFactory.beginTransaction(); res = trackerDAO.getTrackerGroup(groupId, tenantId); - if(res!=null){ + if (res != null) { obj = new JSONObject(res); - if(obj!=null){ + if (obj != null) { trackerDAO.removeTrackerGroup(obj.getInt("id")); TrackerManagementDAOFactory.commitTransaction(); String method = TraccarHandlerConstants.Methods.DELETE; - String url = defaultPort+"/api/groups/"+obj.getInt("traccarGroupId"); + String url = defaultPort + "/api/groups/" + obj.getInt("traccarGroupId"); executor.submit(new OkHttpClientThreadPool(url, null, method, authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), @@ -716,12 +709,12 @@ public class TraccarClientImpl implements TraccarClient { } } catch (TransactionManagementException e) { TrackerManagementDAOFactory.rollbackTransaction(); - msg = "Error occurred establishing the DB connection. "; + String msg = "Error occurred establishing the DB connection. "; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); } catch (TrackerManagementDAOException e) { TrackerManagementDAOFactory.rollbackTransaction(); - msg = "Error occurred while mapping with groupId. "; + String msg = "Error occurred while mapping with groupId. "; log.error(msg, e); throw new TrackerManagementDAOException(msg, e); } finally { @@ -738,27 +731,27 @@ public class TraccarClientImpl implements TraccarClient { return sb.toString(); } - private TraccarGateway getTraccarGateway(){ + 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; + if (trackerUser != null && trackerPassword != null) { + newAuthorizationKey = trackerUser + ':' + trackerPassword; byte[] result = newAuthorizationKey.getBytes(); byte[] res = Base64.encodeBase64(result); - newAuthorizationKey = "Basic " + new String(res); + newAuthorizationKey = "Basic " + new String(res); } return newAuthorizationKey; } public String serverUrl(String serverUrl) { String newServerUri = endpoint; - if(serverUrl!=null){ - newServerUri= serverUrl; + if (serverUrl != null) { + newServerUri = serverUrl; } return newServerUri; } From 83be95358336ba0eb855d715f859fbdc75939dd0 Mon Sep 17 00:00:00 2001 From: shamalka Date: Fri, 2 Sep 2022 00:33:22 +0530 Subject: [PATCH 41/41] Fix issues --- .../service/api/DeviceManagementService.java | 4 +- .../impl/DeviceManagementServiceImpl.java | 28 +++------ .../device/mgt/common/TrackerDeviceInfo.java | 2 +- .../device/mgt/common/TrackerGroupInfo.java | 2 +- .../mgt/common/TrackerPermissionInfo.java | 2 +- .../device/mgt/common/TrackerUserInfo.java | 2 +- .../TrackerAlreadyExistException.java | 4 +- .../device/mgt/core/dao/TrackerDAO.java | 10 ++- .../core/dao/impl/tracker/TrackerDAOImpl.java | 30 +++------ .../dao/util/TrackerManagementDAOUtil.java | 17 ----- .../impl/DeviceInformationManagerImpl.java | 9 ++- .../DeviceManagementProviderServiceImpl.java | 2 + .../api/service/addons/TraccarClientImpl.java | 63 +++++++++---------- .../impl/DeviceAPIClientServiceImpl.java | 2 +- .../common/TraccarHandlerConstants.java | 1 + .../traccar/common/beans/TraccarUser.java | 2 +- .../core/traccar/common/util/TraccarUtil.java | 4 +- 17 files changed, 71 insertions(+), 113 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java index 8ea4cd2f323..07ecbf8a236 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java @@ -588,8 +588,8 @@ public interface DeviceManagementService { @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.", + value = "Getting Details of Registered Devices Owned by an Authenticated User to generate token for Traccar", + notes = "Provides details of devices enrolled by authenticated users to generate token for Traccar.", tags = "Device Management", extensions = { @Extension(properties = { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java index 6600a20c1ba..576dfbf0fa3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -511,17 +511,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { 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); - } + request.setStatusList(status); // this is the user who initiates the request String authorizedUser = MultitenantUtils.getTenantAwareUsername(currentUser); // check whether the user is device-mgt admin @@ -539,9 +529,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { } int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - for (int i = 0; i < devices.getCount(); i++) { - TrackerDeviceInfo trackerDevice = DeviceAPIClientServiceImpl.getTrackerDevice( - devices.getList().get(i).getId(), tenantId); + for (Device device : devices.getList()) { + TrackerDeviceInfo trackerDevice = DeviceAPIClientServiceImpl + .getTrackerDevice(device.getId(), tenantId); int traccarDeviceId = trackerDevice.getTraccarDeviceId(); boolean getPermission = DeviceAPIClientServiceImpl.getUserIdofPermissionByDeviceIdNUserId(traccarDeviceId, userId); traccarValidIdList.add(traccarDeviceId); @@ -549,7 +539,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { DeviceAPIClientServiceImpl.addTrackerUserDevicePermission(userId, traccarDeviceId); } } - //Remove neecessary + //Remove necessary List getAllUserDevices = DeviceAPIClientServiceImpl.getUserIdofPermissionByUserIdNIdList(userId, traccarValidIdList); for (TrackerPermissionInfo getAllUserDevice : getAllUserDevices) { @@ -558,10 +548,6 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { getAllUserDevice.getTraccarDeviceId(), TraccarHandlerConstants.Types.REMOVE_TYPE_SINGLE); } - } catch (JSONException e) { - String msg = "not a JSONObject. "; - log.error(msg); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } catch (DeviceManagementException e) { String msg = "Error occurred while fetching all enrolled devices. "; log.error(msg, e); @@ -575,11 +561,11 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } catch (ExecutionException e) { - String msg = "ExecutionException occurred "; + String msg = "Execution error occurred handling traccar device permissions"; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } catch (InterruptedException e) { - String msg = "InterruptedException occurred "; + String msg = "Interruption error occurred handling traccar device permissions"; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerDeviceInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerDeviceInfo.java index ad55f924298..c97c2a4d9dc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerDeviceInfo.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerDeviceInfo.java @@ -22,7 +22,7 @@ import java.io.Serializable; public class TrackerDeviceInfo implements Serializable { - private static final long serialVersionUID = 1998101712L; + private static final long serialVersionUID = 11545107900391993L; private int id; private int traccarDeviceId; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerGroupInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerGroupInfo.java index 9f7e6b63dee..03a9cfef0c8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerGroupInfo.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerGroupInfo.java @@ -22,7 +22,7 @@ import java.io.Serializable; public class TrackerGroupInfo implements Serializable { - private static final long serialVersionUID = 1998101712L; + private static final long serialVersionUID = 2156646949297006690L; private int id; private int traccarGroupId; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerPermissionInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerPermissionInfo.java index c8509efa291..25341ea19ac 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerPermissionInfo.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerPermissionInfo.java @@ -22,7 +22,7 @@ import java.io.Serializable; public class TrackerPermissionInfo implements Serializable { - private static final long serialVersionUID = 1998101712L; + private static final long serialVersionUID = -8648202903090812913L; private int traccarUserId; private int traccarDeviceId; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerUserInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerUserInfo.java index 4985c601fd9..3354dc4e011 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerUserInfo.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerUserInfo.java @@ -26,7 +26,7 @@ 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; + private static final long serialVersionUID = -6808358733610879805L; @ApiModelProperty(name = "userName", value = "The user's name that can be set on the device by the device user.", required = true) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/exceptions/TrackerAlreadyExistException.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/exceptions/TrackerAlreadyExistException.java index bc7a92684fb..114ab5cb757 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/exceptions/TrackerAlreadyExistException.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/exceptions/TrackerAlreadyExistException.java @@ -23,7 +23,7 @@ package org.wso2.carbon.device.mgt.common.exceptions; */ public class TrackerAlreadyExistException extends Exception { - private static final long serialVersionUID = -312678379574816874L; + private static final long serialVersionUID = 5241722939654800965L; private String errorMessage; public TrackerAlreadyExistException(String msg, Exception nestedEx) { @@ -57,4 +57,4 @@ public class TrackerAlreadyExistException extends Exception { this.errorMessage = errorMessage; } -} \ No newline at end of file +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerDAO.java index 3175b3018e8..c7ce47b0c34 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerDAO.java @@ -34,7 +34,7 @@ public interface TrackerDAO { * @return boolean value. * @throws TrackerManagementDAOException */ - Boolean addTrackerDevice(int traccarDeviceId, int deviceId, int tenantId) throws TrackerManagementDAOException; + void addTrackerDevice(int traccarDeviceId, int deviceId, int tenantId) throws TrackerManagementDAOException; /** * get trackerDevice info. @@ -51,10 +51,9 @@ public interface TrackerDAO { * @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; + void updateTrackerDeviceIdANDStatus(int traccarDeviceId, int deviceId, int tenantId, int status) throws TrackerManagementDAOException; /** * Remove a Device. @@ -63,17 +62,16 @@ public interface TrackerDAO { * @return sql execution result. * @throws TrackerManagementDAOException */ - int removeTrackerDevice(int deviceId, int tenantId) throws TrackerManagementDAOException; + void 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; + void addTrackerGroup(int traccarGroupId, int groupId, int tenantId) throws TrackerManagementDAOException; /** * Update status and traccarGroupId of a Group. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/tracker/TrackerDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/tracker/TrackerDAOImpl.java index d98b630de33..43d21b4d0e9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/tracker/TrackerDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/tracker/TrackerDAOImpl.java @@ -41,7 +41,7 @@ public class TrackerDAOImpl implements TrackerDAO { private static final Log log = LogFactory.getLog(TrackerDAOImpl.class); @Override - public Boolean addTrackerDevice(int traccarDeviceId, int deviceId, int tenantId) + public void addTrackerDevice(int traccarDeviceId, int deviceId, int tenantId) throws TrackerManagementDAOException { PreparedStatement stmt = null; try { @@ -52,8 +52,6 @@ public class TrackerDAOImpl implements TrackerDAO { 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); @@ -64,7 +62,7 @@ public class TrackerDAOImpl implements TrackerDAO { } @Override - public Boolean updateTrackerDeviceIdANDStatus(int traccarDeviceId, int deviceId, int tenantId, int status) + public void updateTrackerDeviceIdANDStatus(int traccarDeviceId, int deviceId, int tenantId, int status) throws TrackerManagementDAOException { PreparedStatement stmt = null; try { @@ -76,8 +74,6 @@ public class TrackerDAOImpl implements TrackerDAO { 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); @@ -88,10 +84,8 @@ public class TrackerDAOImpl implements TrackerDAO { } @Override - public int removeTrackerDevice(int deviceId, int tenantId) throws TrackerManagementDAOException { + public void 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 = ? "; @@ -99,11 +93,6 @@ public class TrackerDAOImpl implements TrackerDAO { 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); @@ -117,7 +106,6 @@ public class TrackerDAOImpl implements TrackerDAO { 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 " + @@ -127,9 +115,9 @@ public class TrackerDAOImpl implements TrackerDAO { stmt.setInt(2, tenantId); rs = stmt.executeQuery(); if (rs.next()) { - trackerDeviceInfo = TrackerManagementDAOUtil.loadTrackerDevice(rs); + return TrackerManagementDAOUtil.loadTrackerDevice(rs); } - return trackerDeviceInfo; + return null; } catch (SQLException e) { String msg = "Error occurred while retrieving data from the trackerDevice table "; log.error(msg, e); @@ -140,10 +128,9 @@ public class TrackerDAOImpl implements TrackerDAO { } @Override - public Boolean addTrackerGroup(int traccarGroupId, int groupId, int tenantId) + public void 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(?, ?, ?, ?)"; @@ -151,10 +138,8 @@ public class TrackerDAOImpl implements TrackerDAO { stmt.setInt(1, traccarGroupId); stmt.setInt(2, groupId); stmt.setInt(3, tenantId); - stmt.setInt(4, status); + stmt.setInt(4, 1); stmt.execute(); - - return true; } catch (SQLException e) { String msg = "Error occurred while adding on traccarGroup mapping table"; log.error(msg, e); @@ -268,6 +253,7 @@ public class TrackerDAOImpl implements TrackerDAO { try { Connection conn = TrackerManagementDAOFactory.getConnection(); String sql = "DELETE FROM DM_EXT_PERMISSION_MAPPING WHERE TRACCAR_DEVICE_ID = ?"; + // TODO: Recheck the usage of below if condition if (removeType != TraccarHandlerConstants.Types.REMOVE_TYPE_MULTIPLE) { sql = sql + " AND TRACCAR_USER_ID = ? "; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/TrackerManagementDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/TrackerManagementDAOUtil.java index fb06d34d012..b36d3ec6683 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/TrackerManagementDAOUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/TrackerManagementDAOUtil.java @@ -1,20 +1,3 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ /* Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. * * Entgra (pvt) Ltd. licenses this file to you under the Apache License, diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java index 553d1c3fa5c..e9e5b0aaf5c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java @@ -395,12 +395,19 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { } catch (ExecutionException e) { log.error("ExecutionException : " + e); //throw new RuntimeException(e); + //Exception was not thrown due to being conflicted with non-traccar features } catch (InterruptedException e) { log.error("InterruptedException : " + e); //throw new RuntimeException(e); + //Exception was not thrown due to being conflicted with non-traccar features } } else { - log.info("location publishing is disabled and traccan disabled"); + if(!HttpReportingUtil.isLocationPublishing()) { + log.info("Location publishing is disabled"); + } + if (!HttpReportingUtil.isTrackerEnabled()) { + log.info("Traccar is disabled"); + } } //Tracker update GPS Location diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index c7f42afb463..c777ea87995 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -441,6 +441,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv //throw new RuntimeException(e); //Exception was not thrown due to being conflicted with non-traccar features } + } else { + log.info("Traccar is disabled"); } //enroll Traccar device diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java index 016e083bf95..526de67f616 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 - 2022 Entgra (Pvt) Ltd, Inc - All Rights Reserved. + * Copyright (C) 2022 Entgra (Pvt) Ltd, Inc - All Rights Reserved. * * Unauthorised copying/redistribution of this file, via any medium is strictly prohibited. * @@ -120,7 +120,7 @@ public class TraccarClientImpl implements TraccarClient { 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) { + if (publisherUrlWithContext.contains("permission")) { requestBody = RequestBody.create(payload.toString(), MediaType.parse("application/json; charset=utf-8")); builder = builder.delete(requestBody); } else { @@ -141,8 +141,7 @@ public class TraccarClientImpl implements TraccarClient { Future result = executor.submit(new OkHttpClientThreadPool(url, null, method, authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), serverUrl(HttpReportingUtil.trackerServer()))); - String res = result.get(); - return res; + return result.get(); } public String fetchUserInfo(String userName) throws ExecutionException, InterruptedException { @@ -177,7 +176,7 @@ public class TraccarClientImpl implements TraccarClient { if (Objects.equals(result, TraccarHandlerConstants.Types.USER_NOT_FOUND)) { //create user - log.info("Creating a user"); + log.info("Creating a user on Traccar client"); traccarUser.setName(userName); traccarUser.setLogin(userName); traccarUser.setEmail(userName); @@ -188,7 +187,7 @@ public class TraccarClientImpl implements TraccarClient { DeviceAPIClientServiceImpl.createUser(traccarUser); } else { //update user - log.info("Updating the user"); + log.info("Updating the user on Traccar client"); JSONObject obj = new JSONObject(result); traccarUser.setId(obj.getInt("id")); @@ -229,8 +228,7 @@ public class TraccarClientImpl implements TraccarClient { Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method, authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), serverUrl(HttpReportingUtil.trackerServer()))); - String result = res.get(); - return result; + return res.get(); } public String updateUser(TraccarUser traccarUser, int userId) throws ExecutionException, InterruptedException { @@ -241,8 +239,7 @@ public class TraccarClientImpl implements TraccarClient { Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method, authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), serverUrl(HttpReportingUtil.trackerServer()))); - String result = res.get(); - return result; + return res.get(); } public void setPermission(int userId, int deviceId) @@ -259,7 +256,7 @@ public class TraccarClientImpl implements TraccarClient { serverUrl(HttpReportingUtil.trackerServer()))); String result = res.get(); - if (result.equals("")) { + if (("").equals(result)) { try { TrackerManagementDAOFactory.beginTransaction(); trackerDAO.addTrackerUserDevicePermission(userId, deviceId); @@ -294,9 +291,8 @@ public class TraccarClientImpl implements TraccarClient { Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method, authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), serverUrl(HttpReportingUtil.trackerServer()))); - String result = res.get(); - if (result != null) { + if (res.get() != null) { try { TrackerManagementDAOFactory.beginTransaction(); trackerDAO.removeTrackerUserDevicePermission(deviceId, userId, removeType); @@ -386,11 +382,6 @@ public class TraccarClientImpl implements TraccarClient { 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); @@ -405,11 +396,10 @@ public class TraccarClientImpl implements TraccarClient { if (trackerDeviceInfo == null) { //add the device - String method = TraccarHandlerConstants.Methods.POST; String url = defaultPort + "/api/devices"; JSONObject payload = TraccarUtil.TraccarDevicePayload(traccarDevice); - Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method, + Future res = executor.submit(new OkHttpClientThreadPool(url, payload, TraccarHandlerConstants.Methods.POST, authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), serverUrl(HttpReportingUtil.trackerServer()))); String result = res.get(); @@ -423,7 +413,7 @@ public class TraccarClientImpl implements TraccarClient { TrackerManagementDAOFactory.beginTransaction(); trackerDAO.addTrackerDevice(traccarDeviceId, deviceId, tenantId); trackerDeviceInfo = trackerDAO.getTrackerDevice(deviceId, tenantId); - if (trackerDeviceInfo.getStatus() == 0) { + if (trackerDeviceInfo != null && trackerDeviceInfo.getStatus() == 0) { trackerDAO.updateTrackerDeviceIdANDStatus(trackerDeviceInfo.getTraccarDeviceId(), deviceId, tenantId, 1); } TrackerManagementDAOFactory.commitTransaction(); @@ -445,6 +435,10 @@ public class TraccarClientImpl implements TraccarClient { setPermission(returnUserInfo.getInt("id"), traccarDeviceId); } } + } else { + String msg = "The device already exist"; + log.error(msg); + throw new TrackerAlreadyExistException(msg); } } @@ -477,14 +471,15 @@ public class TraccarClientImpl implements TraccarClient { addDevice(device, tenantId); } else { //Update Location - log.info("Updating Location"); - String method = TraccarHandlerConstants.Methods.GET; + if (log.isDebugEnabled()) { + log.info("Updating Location of the device: " + device.getId()); + } String url = locationUpdatePort + "/?id=" + deviceInfo.getDeviceIdentifier() + "×tamp=" + deviceInfo.getTimestamp() + "&lat=" + deviceInfo.getLat() + "&lon=" + deviceInfo.getLon() + "&bearing=" + deviceInfo.getBearing() + "&speed=" + deviceInfo.getSpeed() + "&ignition=true"; - executor.submit(new OkHttpClientThreadPool(url, null, method, + executor.submit(new OkHttpClientThreadPool(url, null, TraccarHandlerConstants.Methods.GET, authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), "http://localhost:")); } @@ -502,13 +497,10 @@ public class TraccarClientImpl implements TraccarClient { try { TrackerManagementDAOFactory.beginTransaction(); trackerDeviceInfo = trackerDAO.getTrackerDevice(deviceId, tenantId); - log.info("deviceId - " + deviceId); if (trackerDeviceInfo != null) { - int status = trackerDAO.removeTrackerDevice(deviceId, tenantId); - log.info("Status" + status); + trackerDAO.removeTrackerDevice(deviceId, tenantId); TrackerManagementDAOFactory.commitTransaction(); - trackerPermissionInfo = trackerDAO.getUserIdofPermissionByDeviceId(trackerDeviceInfo.getTraccarDeviceId()); } } catch (TransactionManagementException e) { @@ -524,7 +516,7 @@ public class TraccarClientImpl implements TraccarClient { } finally { TrackerManagementDAOFactory.closeConnection(); } - log.info("--------Disenrolling Device--------"); + log.info("--------Disenrolling Device with device id " + deviceId + " from traccar client--------"); //Delete from traccar if (trackerDeviceInfo != null) { String method = TraccarHandlerConstants.Methods.DELETE; @@ -601,9 +593,9 @@ public class TraccarClientImpl implements TraccarClient { trackerDAO.updateTrackerGroupIdANDStatus(trackerGroupInfo.getTraccarGroupId(), groupId, tenantId, 1); } } catch (TrackerManagementDAOException e) { + TrackerManagementDAOFactory.rollbackTransaction(); String msg = "Error occurred while mapping with deviceId. "; log.error(msg, e); - TrackerManagementDAOFactory.rollbackTransaction(); throw new TrackerManagementDAOException(msg, e); } catch (TransactionManagementException e) { String msg = "Error occurred establishing the DB connection. "; @@ -614,10 +606,12 @@ public class TraccarClientImpl implements TraccarClient { TrackerManagementDAOFactory.closeConnection(); } } else { - log.error("Something went wrong_1: " + result); + // TODO: Assumed the error message change if wrong + log.error("Response does not contains the key id: " + result); } } else { - log.error("Something went wrong_2: " + result); + // TODO: Assumed the error message change if wrong + log.error("Response does not contains a JSON object " + result); } } @@ -636,9 +630,11 @@ public class TraccarClientImpl implements TraccarClient { } catch (SQLException e) { String msg = "Error occurred establishing the DB connection. "; log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); } catch (TrackerManagementDAOException e) { String msg = "Could not find traccar group details. "; log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); } finally { TrackerManagementDAOFactory.closeConnection(); } @@ -699,10 +695,9 @@ public class TraccarClientImpl implements TraccarClient { 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, + executor.submit(new OkHttpClientThreadPool(url, null, TraccarHandlerConstants.Methods.DELETE, authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), serverUrl(HttpReportingUtil.trackerServer()))); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java index 540dcfb8df1..f1f71cb99a8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 - 2022 Entgra (Pvt) Ltd, Inc - All Rights Reserved. + * Copyright (C) 2022 Entgra (Pvt) Ltd, Inc - All Rights Reserved. * * Unauthorised copying/redistribution of this file, via any medium is strictly prohibited. * diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarHandlerConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarHandlerConstants.java index 453fb5290fe..e99832e9398 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarHandlerConstants.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarHandlerConstants.java @@ -31,6 +31,7 @@ public class TraccarHandlerConstants { public static final String LOCATION_UPDATE_PORT = "location-update-port"; } + // TODO: Get these from http client public static class Methods { public static final String POST = "POST"; public static final String GET = "GET"; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarUser.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarUser.java index 37557ef0948..4531e1d122d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarUser.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarUser.java @@ -23,7 +23,7 @@ import java.io.Serializable; public class TraccarUser implements Serializable { - private static final long serialVersionUID = 1998101712L; + private static final long serialVersionUID = -1916365851689588289L; private int id; private String name; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/util/TraccarUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/util/TraccarUtil.java index 6063d4d0c15..986b10624d8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/util/TraccarUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/util/TraccarUtil.java @@ -27,7 +27,7 @@ import java.util.ArrayList; import java.util.List; public class TraccarUtil { - public static JSONObject TraccarUserPayload(TraccarUser traccarUser){ + public static JSONObject TraccarUserPayload(TraccarUser traccarUser) { JSONObject payload = new JSONObject(); JSONObject attribute = new JSONObject(); attribute.put("speedUnit", "kmh"); @@ -48,7 +48,7 @@ public class TraccarUtil { return payload; } - public static JSONObject TraccarDevicePayload(TraccarDevice deviceInfo){ + public static JSONObject TraccarDevicePayload(TraccarDevice deviceInfo) { JSONObject payload = new JSONObject(); payload.put("name", deviceInfo.getDeviceName()); payload.put("uniqueId", deviceInfo.getUniqueId());