Update with okhttclient pool and threading

feature/traccar-sync
Rushdi Mohamed 3 years ago
parent 8d99123ec1
commit 4e3567202d

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

@ -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() +

@ -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;
/**
* 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 disDevice(TraccarDevice deviceInfo) throws IOException;
//String addGroup(TraccarGroups groupInfo) throws IOException;
}

@ -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,136 +30,192 @@ 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);
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();
}
public Request getDeviceByDeviceIdentifier(String deviceId) {
//device identifier matches with traccar uniqueId
//Retrieve the traccar Gateway by passing the Gateway name
TraccarGateway traccarGateway = getTraccarGateway();
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;
}
//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();
public void run() {
RequestBody requestBody;
Request.Builder builder = new Request.Builder();
Request request;
OkHttpClient client = new OkHttpClient().newBuilder().build();
Request request = new Request.Builder()
.url(endpoint+"/devices?uniqueId="+deviceId)
.method("GET", null)
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();
return request;
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 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();
/**
* 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<String> 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);
}
}
OkHttpClient client = new OkHttpClient().newBuilder().build();
Request request = new Request.Builder()
.url(endpoint+"id="+deviceInfo.getDeviceIdentifier()+
"&timestamp="+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(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<String> geofenceIds = new ArrayList<>();
data.put("geofenceIds", geofenceIds);
data.put("attributes", new JSONObject());
RequestBody body = RequestBody.create(mediaType, data.toString());
/**
* 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()+"&timestamp="+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);
}
}
/**
* 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+"/devices")
.method("POST", body)
.addHeader("Content-Type", "application/json")
.url(endpoint+context)
.addHeader(authorization, authorizationKey)
.build();
Response response = client.newCall(request).execute();
return String.valueOf(response);
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);
}
}
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();
OkHttpClient client = new OkHttpClient();
Request deviceDetails = getDeviceByDeviceIdentifier(deviceInfo.getDeviceIdentifier());
Response response = client.newCall(deviceDetails).execute();
String result = response.body().string();
/**
* 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);
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){
log.info("Delete Error "+e);
return String.valueOf(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);
}
}

@ -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));
}*/
}

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

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

@ -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);
}
}
Loading…
Cancel
Save