Add location bean classes and format the source

corrective-policy
tcdlpds@gmail.com 4 years ago
parent 92cca00af0
commit 90dac0a101

@ -108,7 +108,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
private LifecycleStateManager lifecycleStateManager; private LifecycleStateManager lifecycleStateManager;
public SubscriptionManagerImpl() { public SubscriptionManagerImpl() {
lifecycleStateManager = DataHolder.getInstance().getLifecycleStateManager(); this.lifecycleStateManager = DataHolder.getInstance().getLifecycleStateManager();
this.subscriptionDAO = ApplicationManagementDAOFactory.getSubscriptionDAO(); this.subscriptionDAO = ApplicationManagementDAOFactory.getSubscriptionDAO();
this.applicationDAO = ApplicationManagementDAOFactory.getApplicationDAO(); this.applicationDAO = ApplicationManagementDAOFactory.getApplicationDAO();
} }
@ -549,7 +549,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
boolean isValidSubType = Arrays.stream(SubscriptionType.values()) boolean isValidSubType = Arrays.stream(SubscriptionType.values())
.anyMatch(sub -> sub.name().equalsIgnoreCase(subType)); .anyMatch(sub -> sub.name().equalsIgnoreCase(subType));
if (!isValidSubType) { if (!isValidSubType) {
String msg = "Found invalid subscription type " + subType+ " to install application release" ; String msg = "Found invalid subscription type " + subType+ " to subscribe application release" ;
log.error(msg); log.error(msg);
throw new BadRequestException(msg); throw new BadRequestException(msg);
} }
@ -579,8 +579,10 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
ApplicationDTO applicationDTO, String subType, List<String> subscribers, String action) ApplicationDTO applicationDTO, String subType, List<String> subscribers, String action)
throws ApplicationManagementException { throws ApplicationManagementException {
//Get app subscribing info of each device
SubscribingDeviceIdHolder subscribingDeviceIdHolder = getSubscribingDeviceIdHolder(devices, SubscribingDeviceIdHolder subscribingDeviceIdHolder = getSubscribingDeviceIdHolder(devices,
applicationDTO.getApplicationReleaseDTOs().get(0).getId()); applicationDTO.getApplicationReleaseDTOs().get(0).getId());
List<Activity> activityList = new ArrayList<>(); List<Activity> activityList = new ArrayList<>();
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>(); List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
List<DeviceIdentifier> ignoredDeviceIdentifiers = new ArrayList<>(); List<DeviceIdentifier> ignoredDeviceIdentifiers = new ArrayList<>();

@ -504,15 +504,13 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
return Response.status(Response.Status.OK).entity(device).build(); return Response.status(Response.Status.OK).entity(device).build();
} }
@Path("/{deviceType}/{deviceId}/location-history")
@GET @GET
public Response getDeviceLocationInfo(@PathParam("deviceType") String deviceType, @Path("/{deviceType}/{deviceId}/location-history")
public Response getDeviceLocationInfo(
@PathParam("deviceType") String deviceType,
@PathParam("deviceId") String deviceId, @PathParam("deviceId") String deviceId,
@QueryParam("from") long from, @QueryParam("to") long to) { @QueryParam("from") long from,
@QueryParam("to") long to) {
String errorMessage;
DeviceLocationHistory deviceLocationHistory = new DeviceLocationHistory();
try { try {
RequestValidationUtil.validateDeviceIdentifier(deviceType, deviceId); RequestValidationUtil.validateDeviceIdentifier(deviceType, deviceId);
DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService(); DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService();
@ -520,81 +518,81 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
DeviceMgtAPIUtils.getDeviceAccessAuthorizationService(); DeviceMgtAPIUtils.getDeviceAccessAuthorizationService();
String authorizedUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); String authorizedUser = CarbonContext.getThreadLocalCarbonContext().getUsername();
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, deviceType); DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, deviceType);
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(deviceType);
if (!deviceAccessAuthorizationService.isUserAuthorized(deviceIdentifier, authorizedUser)) { if (!deviceAccessAuthorizationService.isUserAuthorized(deviceIdentifier, authorizedUser)) {
String msg = "User '" + authorizedUser + "' is not authorized to retrieve the given device id '" + String msg = "User '" + authorizedUser + "' is not authorized to retrieve the given device id '" +
deviceId + "'"; deviceId + "'";
log.error(msg); log.error(msg);
return Response.status(Response.Status.UNAUTHORIZED).entity( return Response.status(Response.Status.UNAUTHORIZED).entity(new ErrorResponse.ErrorResponseBuilder()
new ErrorResponse.ErrorResponseBuilder().setCode(401l).setMessage(msg).build()).build(); .setCode(Response.Status.UNAUTHORIZED.getStatusCode()).setMessage(msg).build()).build();
} }
if (from == 0 || to == 0) { if (from == 0 || to == 0) {
errorMessage = "Invalid values for from/to"; String msg = "Invalid values for from/to";
log.error(errorMessage); log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity( return Response.status(Response.Status.BAD_REQUEST).entity(new ErrorResponse.ErrorResponseBuilder()
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage)).build(); .setCode(Response.Status.BAD_REQUEST.getStatusCode()).setMessage(msg)).build();
} }
List<List<DeviceLocationHistorySnapshot>> locationHistorySnapshotList = new ArrayList<>();
// Get the location history snapshots for the given period // Get the location history snapshots for the given period
List<DeviceLocationHistorySnapshot> deviceLocationHistorySnapshots = dms.getDeviceLocationInfo(deviceIdentifier, from, to); List<DeviceLocationHistorySnapshot> deviceLocationHistorySnapshots = dms
.getDeviceLocationInfo(deviceIdentifier, from, to);
OperationMonitoringTaskConfig operationMonitoringTaskConfig = dms.getDeviceMonitoringConfig(deviceType); OperationMonitoringTaskConfig operationMonitoringTaskConfig = dms.getDeviceMonitoringConfig(deviceType);
int taskFrequency = operationMonitoringTaskConfig.getFrequency(); int taskFrequency = operationMonitoringTaskConfig.getFrequency();
int operationRecurrentTimes = 0; int operationRecurrentTimes = 0;
List<MonitoringOperation> monitoringOperations = operationMonitoringTaskConfig.getMonitoringOperation(); List<MonitoringOperation> monitoringOperations = operationMonitoringTaskConfig.getMonitoringOperation();
for (MonitoringOperation monitoringOperation : for (MonitoringOperation monitoringOperation : monitoringOperations) {
monitoringOperations) {
if (monitoringOperation.getTaskName().equals("DEVICE_LOCATION")) { if (monitoringOperation.getTaskName().equals("DEVICE_LOCATION")) {
operationRecurrentTimes = monitoringOperation.getRecurrentTimes(); operationRecurrentTimes = monitoringOperation.getRecurrentTimes();
break; break;
} }
} }
// Device Location operation frequency in milliseconds. Adding 100000 ms as an error // Device Location operation frequency in milliseconds. Adding 100000 ms as an error
long operationFrequency = taskFrequency * operationRecurrentTimes + 100000; long operationFrequency = taskFrequency * operationRecurrentTimes + 100000;
Queue<DeviceLocationHistorySnapshot> deviceLocationHistorySnapshotsQueue = new LinkedList<>(
deviceLocationHistorySnapshots);
List<List<DeviceLocationHistorySnapshot>> locationHistorySnapshotList = new ArrayList<>();
Queue<DeviceLocationHistorySnapshot> deviceLocationHistorySnapshotsQueue = new LinkedList<>(deviceLocationHistorySnapshots); while (!deviceLocationHistorySnapshotsQueue.isEmpty()) {
while (deviceLocationHistorySnapshotsQueue.size() > 0) {
List<DeviceLocationHistorySnapshot> snapshots = new ArrayList<>(); List<DeviceLocationHistorySnapshot> snapshots = new ArrayList<>();
// Make a copy of remaining snapshots // Make a copy of remaining snapshots
List<DeviceLocationHistorySnapshot> cachedSnapshots = new ArrayList<>(deviceLocationHistorySnapshotsQueue); List<DeviceLocationHistorySnapshot> cachedSnapshots = new ArrayList<>(
deviceLocationHistorySnapshotsQueue);
for (int i = 0; i < cachedSnapshots.size(); i++) { for (int i = 0; i < cachedSnapshots.size(); i++) {
DeviceLocationHistorySnapshot currentSnapshot = deviceLocationHistorySnapshotsQueue.poll(); DeviceLocationHistorySnapshot currentSnapshot = deviceLocationHistorySnapshotsQueue.poll();
snapshots.add(currentSnapshot); snapshots.add(currentSnapshot);
if (deviceLocationHistorySnapshotsQueue.size() > 0) { if (!deviceLocationHistorySnapshotsQueue.isEmpty()) {
DeviceLocationHistorySnapshot nextSnapshot = deviceLocationHistorySnapshotsQueue.peek(); DeviceLocationHistorySnapshot nextSnapshot = deviceLocationHistorySnapshotsQueue.peek();
if (nextSnapshot.getUpdatedTime().getTime() - currentSnapshot.getUpdatedTime().getTime() > operationFrequency) { if (nextSnapshot.getUpdatedTime().getTime() - currentSnapshot.getUpdatedTime().getTime()
> operationFrequency) {
break; break;
} }
} }
} }
locationHistorySnapshotList.add(snapshots); locationHistorySnapshotList.add(snapshots);
} }
DeviceLocationHistory deviceLocationHistory = new DeviceLocationHistory();
deviceLocationHistory.setLocationHistorySnapshots(locationHistorySnapshotList); deviceLocationHistory.setLocationHistorySnapshots(locationHistorySnapshotList);
return Response.status(Response.Status.OK).entity(deviceLocationHistory).build();
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
errorMessage = "Error occurred while fetching the device information."; String msg = "Error occurred while fetching the device information.";
log.error(errorMessage, e); log.error(msg, e);
return Response.serverError().entity( return Response.serverError().entity(new ErrorResponse.ErrorResponseBuilder()
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()).build(); .setCode(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).setMessage(msg).build()).build();
} catch (DeviceAccessAuthorizationException e) { } catch (DeviceAccessAuthorizationException e) {
errorMessage = "Error occurred while checking the device authorization."; String msg = "Error occurred while checking the device authorization.";
log.error(errorMessage, e); log.error(msg, e);
return Response.serverError().entity( return Response.serverError().entity(new ErrorResponse.ErrorResponseBuilder()
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()).build(); .setCode(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).setMessage(msg).build()).build();
} catch (InputValidationException e){ } catch (InputValidationException e) {
errorMessage = "Invalid device Id or device type"; String msg = "Invalid device Id or device type";
log.error(errorMessage, e); log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity( return Response.status(Response.Status.BAD_REQUEST).entity(new ErrorResponse.ErrorResponseBuilder()
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage)).build(); .setCode(Response.Status.BAD_REQUEST.getStatusCode()).setMessage(msg)).build();
} }
return Response.status(Response.Status.OK).entity(deviceLocationHistory).build();
} }
@GET @GET

@ -0,0 +1,89 @@
/*
* Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
*
* Entgra (pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.common.device.details;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.List;
@ApiModel(
value = "LocationBean",
description = "This class carries all information related IOS Device location."
)
public class LocationBean {
@ApiModelProperty(
name = "latitude",
value = "Latitude of the IOS device Location.",
required = true
)
private float latitude;
@ApiModelProperty(
name = "longitude",
value = "Longitude of the IOS device Location.",
required = true
)
private float longitude;
@ApiModelProperty(
name = "operationId",
value = "Specific Id of the Location operation.",
required = true
)
private String operationId;
@ApiModelProperty(
name = "locationEvents",
value = "If this is a device initiated location publishing."
)
private List<LocationEventBean> locations;
public List<LocationEventBean> getLocationEvents() {
return locations;
}
public void setLocationEvents(List<LocationEventBean> locationEvents) {
this.locations = locationEvents;
}
public String getOperationId() {
return operationId;
}
public void setOperationId(String operationId) {
this.operationId = operationId;
}
public float getLatitude() {
return latitude;
}
public void setLatitude(float latitude) {
this.latitude = latitude;
}
public float getLongitude() {
return longitude;
}
public void setLongitude(float longitude) {
this.longitude = longitude;
}
}

@ -0,0 +1,69 @@
/*
* Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
*
* Entgra (pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.common.device.details;
import io.swagger.annotations.ApiModelProperty;
public class LocationEventBean {
@ApiModelProperty(
name = "latitude",
value = "Latitude of the IOS device Location.",
required = true
)
private String latitude;
@ApiModelProperty(
name = "longitude",
value = "Longitude of the IOS device Location.",
required = true
)
private String longitude;
@ApiModelProperty(
name = "timestamp",
value = "Device Location time.",
required = true
)
private String timestamp;
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
}

@ -1830,40 +1830,45 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
} }
@Override @Override
public List<DeviceLocationHistorySnapshot> getDeviceLocationInfo(DeviceIdentifier deviceIdentifier, long from, long to) public List<DeviceLocationHistorySnapshot> getDeviceLocationInfo(DeviceIdentifier deviceIdentifier, long from,
throws DeviceManagementDAOException { long to) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
List<DeviceLocationHistorySnapshot> deviceLocationHistories = new ArrayList<>(); List<DeviceLocationHistorySnapshot> deviceLocationHistories = new ArrayList<>();
String sql = "SELECT "
+ "DEVICE_ID, "
+ "TENANT_ID, "
+ "DEVICE_ID_NAME, "
+ "DEVICE_TYPE_NAME, "
+ "LATITUDE, "
+ "LONGITUDE, "
+ "SPEED, "
+ "HEADING, "
+ "TIMESTAMP, "
+ "GEO_HASH, "
+ "DEVICE_OWNER, "
+ "DEVICE_ALTITUDE, "
+ "DISTANCE "
+ "FROM DM_DEVICE_HISTORY_LAST_SEVEN_DAYS "
+ "WHERE "
+ "DEVICE_ID_NAME = ? AND "
+ "DEVICE_TYPE_NAME = ? AND "
+ "TIMESTAMP BETWEEN ? AND ?";
try { try {
conn = this.getConnection(); Connection conn = this.getConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
String sql =
"SELECT DEVICE_ID, TENANT_ID, DEVICE_ID_NAME, DEVICE_TYPE_NAME, LATITUDE, LONGITUDE, SPEED, " +
"HEADING, TIMESTAMP, GEO_HASH, DEVICE_OWNER, DEVICE_ALTITUDE, DISTANCE " +
"FROM DM_DEVICE_HISTORY_LAST_SEVEN_DAYS " +
"WHERE DEVICE_ID_NAME = ? " +
"AND DEVICE_TYPE_NAME = ? " +
"AND TIMESTAMP >= ? " +
"AND TIMESTAMP <= ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, deviceIdentifier.getId()); stmt.setString(1, deviceIdentifier.getId());
stmt.setString(2, deviceIdentifier.getType()); stmt.setString(2, deviceIdentifier.getType());
stmt.setLong(3, from); stmt.setLong(3, from);
stmt.setLong(4, to); stmt.setLong(4, to);
rs = stmt.executeQuery(); try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) { while (rs.next()) {
deviceLocationHistories.add(DeviceManagementDAOUtil.loadDeviceLocation(rs)); deviceLocationHistories.add(DeviceManagementDAOUtil.loadDeviceLocation(rs));
} }
}
}
} catch (SQLException e) { } catch (SQLException e) {
String errMessage = "Error occurred while obtaining the DB connection to get device location information"; String msg = "Error occurred while obtaining the DB connection to get device location information";
log.error(errMessage, e); log.error(msg, e);
throw new DeviceManagementDAOException(errMessage, e); throw new DeviceManagementDAOException(msg, e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
} }
return deviceLocationHistories; return deviceLocationHistories;
} }

@ -3051,26 +3051,21 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
} }
@Override @Override
public List<DeviceLocationHistorySnapshot> getDeviceLocationInfo(DeviceIdentifier deviceIdentifier, long from, long to) public List<DeviceLocationHistorySnapshot> getDeviceLocationInfo(DeviceIdentifier deviceIdentifier, long from,
throws DeviceManagementException { long to) throws DeviceManagementException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Get device location information"); log.debug("Get device location information");
} }
List<DeviceLocationHistorySnapshot> deviceLocationHistory; List<DeviceLocationHistorySnapshot> deviceLocationHistory;
String errMessage;
try { try {
DeviceManagementDAOFactory.openConnection(); DeviceManagementDAOFactory.openConnection();
deviceLocationHistory = deviceDAO.getDeviceLocationInfo(deviceIdentifier, from, to); deviceLocationHistory = deviceDAO.getDeviceLocationInfo(deviceIdentifier, from, to);
} catch (DeviceManagementDAOException e) { } catch (DeviceManagementDAOException e) {
errMessage = "Error occurred in getDeviceLocationInfo"; String errMessage = "Error occurred in getDeviceLocationInfo";
log.error(errMessage, e); log.error(errMessage, e);
throw new DeviceManagementException(errMessage, e); throw new DeviceManagementException(errMessage, e);
} catch (SQLException e) { } catch (SQLException e) {
errMessage = "Error occurred while opening a connection to the data source"; String errMessage = "Error occurred while opening a connection to the data source";
log.error(errMessage, e); log.error(errMessage, e);
throw new DeviceManagementException(errMessage, e); throw new DeviceManagementException(errMessage, e);
} finally { } finally {

@ -148,6 +148,8 @@
<Scope>perm:user:permission-view</Scope> <Scope>perm:user:permission-view</Scope>
<Scope>perm:ios:view-configuration</Scope> <Scope>perm:ios:view-configuration</Scope>
<Scope>perm:ios:manage-configuration</Scope> <Scope>perm:ios:manage-configuration</Scope>
<Scope>perm:ios:dep-view</Scope>
<Scope>perm:ios:dep-add</Scope>
<Scope>perm:windows:view-configuration</Scope> <Scope>perm:windows:view-configuration</Scope>
<Scope>perm:windows:manage-configuration</Scope> <Scope>perm:windows:manage-configuration</Scope>
<Scope>perm:android:lock-devices</Scope> <Scope>perm:android:lock-devices</Scope>

Loading…
Cancel
Save