Search in sources :

Example 6 with Device

use of org.wso2.carbon.device.mgt.common.Device in project product-iots by wso2.

the class ConnectedCupManager method disenrollDevice.

@Override
public boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
    boolean status;
    try {
        if (log.isDebugEnabled()) {
            log.debug("Dis-enrolling Connected Cup device : " + deviceId);
        }
        ConnectedCupDAOUtil.beginTransaction();
        status = CONNECTED_CUP_DAO_UTIL.getConnectedCupDeviceDAO().deleteDevice(deviceId.getId());
        ConnectedCupDAOUtil.commitTransaction();
    } catch (ConnectedCupDeviceMgtPluginException e) {
        try {
            ConnectedCupDAOUtil.rollbackTransaction();
        } catch (ConnectedCupDeviceMgtPluginException iotDAOEx) {
            String msg = "Error occurred while roll back the device dis enrol transaction :" + deviceId.toString();
            log.warn(msg, iotDAOEx);
        }
        String msg = "Error while removing the Connected Cup device : " + deviceId.getId();
        log.error(msg, e);
        throw new DeviceManagementException(msg, e);
    }
    return status;
}
Also used : ConnectedCupDeviceMgtPluginException(org.coffeeking.connectedcup.plugin.exception.ConnectedCupDeviceMgtPluginException) DeviceManagementException(org.wso2.carbon.device.mgt.common.DeviceManagementException)

Example 7 with Device

use of org.wso2.carbon.device.mgt.common.Device in project product-iots by wso2.

the class DeviceTypeServiceImpl method getSensorStats.

/**
 * Retrieve Sensor data for the given time period.
 *
 * @param deviceId unique identifier for given device type instance
 * @param from     starting time
 * @param to       ending time
 * @return response with List<SensorRecord> object which includes sensor data which is requested
 */
@Path("device/stats/{deviceId}")
@GET
@Consumes("application/json")
@Produces("application/json")
public Response getSensorStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from, @QueryParam("to") long to, @QueryParam("sensorType") String sensorType) {
    String fromDate = String.valueOf(from);
    String toDate = String.valueOf(to);
    String query = "meta_deviceId:" + deviceId + " AND meta_deviceType:" + DeviceTypeConstants.DEVICE_TYPE + " AND meta_time : [" + fromDate + " TO " + toDate + "]";
    String sensorTableName = null;
    if (sensorType.equals(DeviceTypeConstants.SENSOR_TYPE1)) {
        sensorTableName = DeviceTypeConstants.SENSOR_TYPE1_EVENT_TABLE;
    } else if (sensorType.equals(DeviceTypeConstants.SENSOR_TYPE2)) {
        sensorTableName = DeviceTypeConstants.SENSOR_TYPE2_EVENT_TABLE;
    }
    try {
        if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, DeviceTypeConstants.DEVICE_TYPE))) {
            return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
        }
        if (sensorTableName != null) {
            List<SortByField> sortByFields = new ArrayList<>();
            SortByField sortByField = new SortByField("meta_time", SortType.ASC);
            sortByFields.add(sortByField);
            List<SensorRecord> sensorRecords = APIUtil.getAllEventsForDevice(sensorTableName, query, sortByFields);
            return Response.status(Response.Status.OK.getStatusCode()).entity(sensorRecords).build();
        }
    } catch (AnalyticsException e) {
        String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
        log.error(errorMsg);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build();
    } catch (DeviceAccessAuthorizationException e) {
        log.error(e.getErrorMessage(), e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    }
    return Response.status(Response.Status.BAD_REQUEST).build();
}
Also used : SortByField(org.wso2.carbon.analytics.dataservice.commons.SortByField) DeviceAccessAuthorizationException(org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException) AnalyticsException(org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException) ArrayList(java.util.ArrayList) SensorRecord(org.wso2.iot.sampledevice.api.dto.SensorRecord) DeviceIdentifier(org.wso2.carbon.device.mgt.common.DeviceIdentifier) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 8 with Device

use of org.wso2.carbon.device.mgt.common.Device in project product-iots by wso2.

the class DeviceTypeServiceImpl method downloadSketch.

/**
 * To download device type agent source code as zip file.
 *
 * @param deviceName name for the device type instance
 * @param sketchType folder name where device type agent was installed into server
 * @return Agent source code as zip file
 */
@Path("/device/download")
@GET
@Produces("application/zip")
public Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketchType") String sketchType) {
    try {
        ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
        Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
        response.status(Response.Status.OK);
        response.type("application/zip");
        response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
        Response resp = response.build();
        zipFile.getZipFile().delete();
        return resp;
    } catch (IllegalArgumentException ex) {
        // bad request
        return Response.status(400).entity(ex.getMessage()).build();
    } catch (DeviceManagementException ex) {
        log.error(ex.getMessage(), ex);
        return Response.status(500).entity(ex.getMessage()).build();
    } catch (JWTClientException ex) {
        log.error(ex.getMessage(), ex);
        return Response.status(500).entity(ex.getMessage()).build();
    } catch (APIManagerException ex) {
        log.error(ex.getMessage(), ex);
        return Response.status(500).entity(ex.getMessage()).build();
    } catch (IOException ex) {
        log.error(ex.getMessage(), ex);
        return Response.status(500).entity(ex.getMessage()).build();
    } catch (UserStoreException ex) {
        log.error(ex.getMessage(), ex);
        return Response.status(500).entity(ex.getMessage()).build();
    }
}
Also used : Response(javax.ws.rs.core.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) DeviceManagementException(org.wso2.carbon.device.mgt.common.DeviceManagementException) APIManagerException(org.wso2.carbon.apimgt.application.extension.exception.APIManagerException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) ZipArchive(org.wso2.iot.sampledevice.api.util.ZipArchive) IOException(java.io.IOException) JWTClientException(org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 9 with Device

use of org.wso2.carbon.device.mgt.common.Device in project product-iots by wso2.

the class APIUtil method getDeviceAccessAuthorizationService.

/**
 * @return A Service to authorize device access requests
 */
public static DeviceAccessAuthorizationService getDeviceAccessAuthorizationService() {
    PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    DeviceAccessAuthorizationService deviceAccessAuthorizationService = (DeviceAccessAuthorizationService) ctx.getOSGiService(DeviceAccessAuthorizationService.class, null);
    if (deviceAccessAuthorizationService == null) {
        String msg = "Device Authorization service has not initialized.";
        log.error(msg);
        throw new IllegalStateException(msg);
    }
    return deviceAccessAuthorizationService;
}
Also used : DeviceAccessAuthorizationService(org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext)

Example 10 with Device

use of org.wso2.carbon.device.mgt.common.Device in project product-iots by wso2.

the class APIUtil method getAllEventsForDevice.

/**
 * Get sensor data for a device.
 *
 * @param tableName    table name of the data source
 * @param query        query for the table
 * @param sortByFields list of fields to sort the data by
 * @return List of SensorRecords that is sorted by the fields provided
 * @throws AnalyticsException
 */
public static List<SensorRecord> getAllEventsForDevice(String tableName, String query, List<SortByField> sortByFields) throws AnalyticsException {
    int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    AnalyticsDataAPI analyticsDataAPI = getAnalyticsDataAPI();
    int eventCount = analyticsDataAPI.searchCount(tenantId, tableName, query);
    if (eventCount == 0) {
        return null;
    }
    List<SearchResultEntry> resultEntries = analyticsDataAPI.search(tenantId, tableName, query, 0, eventCount, sortByFields);
    List<String> recordIds = getRecordIds(resultEntries);
    AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, null, recordIds);
    Map<String, SensorRecord> sensorDatas = createSensorData(AnalyticsDataAPIUtil.listRecords(analyticsDataAPI, response));
    List<SensorRecord> sortedSensorData = getSortedSensorData(sensorDatas, resultEntries);
    return sortedSensorData;
}
Also used : SensorRecord(org.wso2.iot.sampledevice.api.dto.SensorRecord) AnalyticsDataResponse(org.wso2.carbon.analytics.dataservice.commons.AnalyticsDataResponse) AnalyticsDataAPI(org.wso2.carbon.analytics.api.AnalyticsDataAPI) SearchResultEntry(org.wso2.carbon.analytics.dataservice.commons.SearchResultEntry)

Aggregations

Test (org.testng.annotations.Test)20 HttpResponse (org.wso2.carbon.automation.test.utils.http.client.HttpResponse)17 DeviceManagementException (org.wso2.carbon.device.mgt.common.DeviceManagementException)13 DeviceMgtPluginException (org.wso2.iot.sampledevice.plugin.exception.DeviceMgtPluginException)11 JsonParser (com.google.gson.JsonParser)10 SQLException (java.sql.SQLException)8 JsonObject (com.google.gson.JsonObject)7 Connection (java.sql.Connection)7 PreparedStatement (java.sql.PreparedStatement)7 HashMap (java.util.HashMap)6 ConnectedCupDeviceMgtPluginException (org.coffeeking.connectedcup.plugin.exception.ConnectedCupDeviceMgtPluginException)6 Device (org.wso2.carbon.device.mgt.common.Device)6 JsonArray (com.google.gson.JsonArray)5 JsonElement (com.google.gson.JsonElement)4 ResultSet (java.sql.ResultSet)4 ArrayList (java.util.ArrayList)4 Path (javax.ws.rs.Path)4 JSONObject (org.json.simple.JSONObject)4 PrivilegedCarbonContext (org.wso2.carbon.context.PrivilegedCarbonContext)4 DeviceIdentifier (org.wso2.carbon.device.mgt.common.DeviceIdentifier)4