application-manager-new
charitha 8 years ago
parent 66470f145b
commit 0a61e29641

@ -25,13 +25,11 @@ import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.GET; import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST; import javax.ws.rs.POST;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import javax.ws.rs.Produces; import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam; import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
@API(name = "connectedcup", version = "1.0.0", context = "/connectedcup", tags = {"connectedcup"}) @API(name = "connectedcup", version = "1.0.0", context = "/connectedcup", tags = {"connectedcup"})
@ -53,7 +51,7 @@ public interface ConnectedCupService {
@Produces("application/json") @Produces("application/json")
@Permission(scope = "connectedcup_user", permissions = {"/permission/admin/device-mgt/user/stats"}) @Permission(scope = "connectedcup_user", permissions = {"/permission/admin/device-mgt/user/stats"})
Response getDeviceStats(@PathParam("deviceId") String deviceId, @PathParam("sensorName") String sensor, Response getDeviceStats(@PathParam("deviceId") String deviceId, @PathParam("sensorName") String sensor,
@QueryParam("from") long from, @QueryParam("to") long to); @QueryParam("from") long from, @QueryParam("to") long to);
@Path("device/register") @Path("device/register")
@POST @POST

@ -23,14 +23,14 @@ import org.apache.commons.logging.LogFactory;
import org.coffeeking.api.util.APIUtil; import org.coffeeking.api.util.APIUtil;
import org.coffeeking.api.util.SensorRecord; import org.coffeeking.api.util.SensorRecord;
import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants; import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants;
import org.wso2.carbon.analytics.dataservice.commons.SORT;
import org.wso2.carbon.analytics.dataservice.commons.SortByField;
import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.analytics.dataservice.commons.SORT;
import org.wso2.carbon.analytics.dataservice.commons.SortByField;
import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
@ -52,13 +52,19 @@ public class ConnectedCupServiceImpl implements ConnectedCupService {
private static Log log = LogFactory.getLog(ConnectedCupServiceImpl.class); private static Log log = LogFactory.getLog(ConnectedCupServiceImpl.class);
private static String shortUUID() {
UUID uuid = UUID.randomUUID();
long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
return Long.toString(l, Character.MAX_RADIX);
}
@Path("device/ordercoffee") @Path("device/ordercoffee")
@POST @POST
public Response orderCoffee(@QueryParam("deviceId") String deviceId) { public Response orderCoffee(@QueryParam("deviceId") String deviceId) {
try { try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, if (!APIUtil.getDeviceAccessAuthorizationService()
ConnectedCupConstants.DEVICE_TYPE), DeviceGroupConstants.Permissions. .isUserAuthorized(new DeviceIdentifier(deviceId, ConnectedCupConstants.DEVICE_TYPE),
DEFAULT_OPERATOR_PERMISSIONS)) { DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} }
log.info("Coffee ordered....!"); log.info("Coffee ordered....!");
@ -77,16 +83,17 @@ public class ConnectedCupServiceImpl implements ConnectedCupService {
@Consumes("application/json") @Consumes("application/json")
@Produces("application/json") @Produces("application/json")
public Response getDeviceStats(@PathParam("deviceId") String deviceId, @PathParam("sensorName") String sensor, public Response getDeviceStats(@PathParam("deviceId") String deviceId, @PathParam("sensorName") String sensor,
@QueryParam("from") long from, @QueryParam("to") long to) { @QueryParam("from") long from, @QueryParam("to") long to) {
String fromDate = String.valueOf(from); String fromDate = String.valueOf(from);
String toDate = String.valueOf(to); String toDate = String.valueOf(to);
String query = " deviceId:" + deviceId + " AND deviceType:" + String query = " deviceId:" + deviceId + " AND deviceType:" +
ConnectedCupConstants.DEVICE_TYPE + " AND time : [" + fromDate + " TO " + toDate + "]"; ConnectedCupConstants.DEVICE_TYPE + " AND time : [" + fromDate + " TO " + toDate + "]";
String sensorTableName = getSensorEventTableName(sensor); String sensorTableName = getSensorEventTableName(sensor);
try { try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, if (!APIUtil.getDeviceAccessAuthorizationService()
ConnectedCupConstants.DEVICE_TYPE), DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) { .isUserAuthorized(new DeviceIdentifier(deviceId, ConnectedCupConstants.DEVICE_TYPE),
DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} }
List<SensorRecord> sensorDatas; List<SensorRecord> sensorDatas;
@ -151,10 +158,4 @@ public class ConnectedCupServiceImpl implements ConnectedCupService {
} }
} }
private static String shortUUID() {
UUID uuid = UUID.randomUUID();
long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
return Long.toString(l, Character.MAX_RADIX);
}
} }

@ -11,7 +11,7 @@
* Unless required by applicable law or agreed to in writing, * Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an * software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * "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 * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
@ -20,10 +20,6 @@ package org.coffeeking.api.util;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.analytics.api.AnalyticsDataAPI; import org.wso2.carbon.analytics.api.AnalyticsDataAPI;
import org.wso2.carbon.analytics.dataservice.commons.AnalyticsDataResponse; import org.wso2.carbon.analytics.dataservice.commons.AnalyticsDataResponse;
import org.wso2.carbon.analytics.dataservice.commons.SearchResultEntry; import org.wso2.carbon.analytics.dataservice.commons.SearchResultEntry;
@ -31,6 +27,10 @@ import org.wso2.carbon.analytics.dataservice.commons.SortByField;
import org.wso2.carbon.analytics.dataservice.core.AnalyticsDataServiceUtils; import org.wso2.carbon.analytics.dataservice.core.AnalyticsDataServiceUtils;
import org.wso2.carbon.analytics.datasource.commons.Record; import org.wso2.carbon.analytics.datasource.commons.Record;
import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException; import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
@ -42,114 +42,108 @@ import java.util.Map;
*/ */
public class APIUtil { public class APIUtil {
private static Log log = LogFactory.getLog(APIUtil.class); private static Log log = LogFactory.getLog(APIUtil.class);
public static String getAuthenticatedUser() { public static String getAuthenticatedUser() {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
String username = threadLocalCarbonContext.getUsername(); String username = threadLocalCarbonContext.getUsername();
String tenantDomain = threadLocalCarbonContext.getTenantDomain(); String tenantDomain = threadLocalCarbonContext.getTenantDomain();
if (username.endsWith(tenantDomain)) { if (username.endsWith(tenantDomain)) {
return username.substring(0, username.lastIndexOf("@")); return username.substring(0, username.lastIndexOf("@"));
} }
return username; return username;
} }
public static DeviceManagementProviderService getDeviceManagementService() { public static DeviceManagementProviderService getDeviceManagementService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceManagementProviderService deviceManagementProviderService = DeviceManagementProviderService deviceManagementProviderService =
(DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null); (DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null);
if (deviceManagementProviderService == null) { if (deviceManagementProviderService == null) {
String msg = "Device Management service has not initialized."; throw new IllegalStateException("Device Management service has not initialized");
log.error(msg); }
throw new IllegalStateException(msg); return deviceManagementProviderService;
} }
return deviceManagementProviderService;
}
public static DeviceAccessAuthorizationService getDeviceAccessAuthorizationService() { public static DeviceAccessAuthorizationService getDeviceAccessAuthorizationService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceAccessAuthorizationService deviceAccessAuthorizationService = DeviceAccessAuthorizationService deviceAccessAuthorizationService =
(DeviceAccessAuthorizationService) ctx.getOSGiService(DeviceAccessAuthorizationService.class, null); (DeviceAccessAuthorizationService) ctx.getOSGiService(DeviceAccessAuthorizationService.class, null);
if (deviceAccessAuthorizationService == null) { if (deviceAccessAuthorizationService == null) {
String msg = "Device Authorization service has not initialized."; throw new IllegalStateException("Device Authorization service has not initialized");
log.error(msg); }
throw new IllegalStateException(msg); return deviceAccessAuthorizationService;
} }
return deviceAccessAuthorizationService;
}
public static AnalyticsDataAPI getAnalyticsDataAPI() { public static AnalyticsDataAPI getAnalyticsDataAPI() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
AnalyticsDataAPI analyticsDataAPI = AnalyticsDataAPI analyticsDataAPI =
(AnalyticsDataAPI) ctx.getOSGiService(AnalyticsDataAPI.class, null); (AnalyticsDataAPI) ctx.getOSGiService(AnalyticsDataAPI.class, null);
if (analyticsDataAPI == null) { if (analyticsDataAPI == null) {
String msg = "Analytics api service has not initialized."; throw new IllegalStateException("Analytics api service has not initialized");
log.error(msg); }
throw new IllegalStateException(msg); return analyticsDataAPI;
} }
return analyticsDataAPI;
}
public static List<SensorRecord> getAllEventsForDevice(String tableName, String query, public static List<SensorRecord> getAllEventsForDevice(String tableName, String query,
List<SortByField> sortByFields) throws AnalyticsException { List<SortByField> sortByFields) throws AnalyticsException {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
AnalyticsDataAPI analyticsDataAPI = getAnalyticsDataAPI(); AnalyticsDataAPI analyticsDataAPI = getAnalyticsDataAPI();
int eventCount = analyticsDataAPI.searchCount(tenantId, tableName, query); int eventCount = analyticsDataAPI.searchCount(tenantId, tableName, query);
if (eventCount == 0) { if (eventCount == 0) {
return null; return null;
} }
List<SearchResultEntry> resultEntries = analyticsDataAPI.search(tenantId, tableName, query, 0, eventCount, List<SearchResultEntry> resultEntries = analyticsDataAPI.search(tenantId, tableName, query, 0, eventCount,
sortByFields); sortByFields);
List<String> recordIds = getRecordIds(resultEntries); List<String> recordIds = getRecordIds(resultEntries);
AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, null, recordIds); AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, null, recordIds);
Map<String, SensorRecord> sensorDatas = createSensorData(AnalyticsDataServiceUtils.listRecords( Map<String, SensorRecord> sensorDatas = createSensorData(AnalyticsDataServiceUtils.listRecords(
analyticsDataAPI, response)); analyticsDataAPI, response));
List<SensorRecord> sortedSensorData = getSortedSensorData(sensorDatas, resultEntries); List<SensorRecord> sortedSensorData = getSortedSensorData(sensorDatas, resultEntries);
return sortedSensorData; return sortedSensorData;
} }
private static List<String> getRecordIds(List<SearchResultEntry> searchResults) { private static List<String> getRecordIds(List<SearchResultEntry> searchResults) {
List<String> ids = new ArrayList<>(); List<String> ids = new ArrayList<>();
for (SearchResultEntry searchResult : searchResults) { for (SearchResultEntry searchResult : searchResults) {
ids.add(searchResult.getId()); ids.add(searchResult.getId());
} }
return ids; return ids;
} }
public static List<SensorRecord> getSortedSensorData(Map<String, SensorRecord> sensorDatas, public static List<SensorRecord> getSortedSensorData(Map<String, SensorRecord> sensorDatas,
List<SearchResultEntry> searchResults) { List<SearchResultEntry> searchResults) {
List<SensorRecord> sortedRecords = new ArrayList<>(); List<SensorRecord> sortedRecords = new ArrayList<>();
for (SearchResultEntry searchResultEntry : searchResults) { for (SearchResultEntry searchResultEntry : searchResults) {
sortedRecords.add(sensorDatas.get(searchResultEntry.getId())); sortedRecords.add(sensorDatas.get(searchResultEntry.getId()));
} }
return sortedRecords; return sortedRecords;
} }
/** /**
* Creates the SensorDatas from records. * Creates the SensorDatas from records.
* *
* @param records the records * @param records the records
* @return the Map of SensorRecord <id, SensorRecord> * @return the Map of SensorRecord <id, SensorRecord>
*/ */
public static Map<String, SensorRecord> createSensorData(List<Record> records) { public static Map<String, SensorRecord> createSensorData(List<Record> records) {
Map<String, SensorRecord> sensorDatas = new HashMap<>(); Map<String, SensorRecord> sensorDatas = new HashMap<>();
for (Record record : records) { for (Record record : records) {
SensorRecord sensorData = createSensorData(record); SensorRecord sensorData = createSensorData(record);
sensorDatas.put(sensorData.getId(), sensorData); sensorDatas.put(sensorData.getId(), sensorData);
} }
return sensorDatas; return sensorDatas;
} }
/** /**
* Create a SensorRecord object out of a Record object * Create a SensorRecord object out of a Record object
* *
* @param record the record object * @param record the record object
* @return SensorRecord object * @return SensorRecord object
*/ */
public static SensorRecord createSensorData(Record record) { public static SensorRecord createSensorData(Record record) {
SensorRecord recordBean = new SensorRecord(); SensorRecord recordBean = new SensorRecord();
recordBean.setId(record.getId()); recordBean.setId(record.getId());
recordBean.setValues(record.getValues()); recordBean.setValues(record.getValues());
return recordBean; return recordBean;
} }
} }

@ -37,12 +37,12 @@ public class SensorRecord {
@XmlElementWrapper(required = true, name = "values") @XmlElementWrapper(required = true, name = "values")
private Map<String, Object> values; private Map<String, Object> values;
/** The id. */
@XmlElement(required = false, name = "id") @XmlElement(required = false, name = "id")
private String id; private String id;
/** /**
* Gets the values. * Gets the values.
*
* @return the values * @return the values
*/ */
public Map<String, Object> getValues() { public Map<String, Object> getValues() {
@ -51,30 +51,33 @@ public class SensorRecord {
/** /**
* Sets the values. * Sets the values.
*
* @param values the values * @param values the values
*/ */
public void setValues(Map<String, Object> values) { public void setValues(Map<String, Object> values) {
this.values = values; this.values = values;
} }
/**
* Sets the id.
* @param id the new id
*/
public void setId(String id) {
this.id = id;
}
/** /**
* Gets the id. * Gets the id.
*
* @return the id * @return the id
*/ */
public String getId() { public String getId() {
return id; return id;
} }
/**
* Sets the id.
*
* @param id the new id
*/
public void setId(String id) {
this.id = id;
}
@Override @Override
public String toString(){ public String toString() {
List<String> valueList = new ArrayList<String>(); List<String> valueList = new ArrayList<String>();
for (Map.Entry<String, Object> entry : values.entrySet()) { for (Map.Entry<String, Object> entry : values.entrySet()) {
valueList.add(entry.getKey() + ":" + entry.getValue()); valueList.add(entry.getKey() + ":" + entry.getValue());

@ -18,6 +18,7 @@
package org.coffeeking.connectedcup.plugin.constants; package org.coffeeking.connectedcup.plugin.constants;
public class ConnectedCupConstants { public class ConnectedCupConstants {
public final static String DEVICE_TYPE = "connectedcup"; public final static String DEVICE_TYPE = "connectedcup";
public final static String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME"; public final static String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME";
public final static String DEVICE_PLUGIN_DEVICE_ID = "CONNECTED_CUP_DEVICE_ID"; public final static String DEVICE_PLUGIN_DEVICE_ID = "CONNECTED_CUP_DEVICE_ID";

@ -17,19 +17,10 @@
*/ */
package org.coffeeking.connectedcup.plugin.exception; package org.coffeeking.connectedcup.plugin.exception;
public class ConnectedCupDeviceMgtPluginException extends Exception {
public class ConnectedCupDeviceMgtPluginException extends Exception{
private String errorMessage; private String errorMessage;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public ConnectedCupDeviceMgtPluginException(String msg, Exception nestedEx) { public ConnectedCupDeviceMgtPluginException(String msg, Exception nestedEx) {
super(msg, nestedEx); super(msg, nestedEx);
setErrorMessage(msg); setErrorMessage(msg);
@ -53,4 +44,12 @@ public class ConnectedCupDeviceMgtPluginException extends Exception{
super(cause); super(cause);
} }
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
} }

@ -44,7 +44,7 @@ public class ConnectedCupServiceComponent {
BundleContext bundleContext = ctx.getBundleContext(); BundleContext bundleContext = ctx.getBundleContext();
connectedCupServiceRegRef = connectedCupServiceRegRef =
bundleContext.registerService(DeviceManagementService.class.getName(), bundleContext.registerService(DeviceManagementService.class.getName(),
new ConnectedCupManagerService(), null); new ConnectedCupManagerService(), null);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Connected Cup Service Component has been successfully activated"); log.debug("Connected Cup Service Component has been successfully activated");
@ -70,4 +70,5 @@ public class ConnectedCupServiceComponent {
log.error("Error occurred while de-activating Connected Cup Service Component", e); log.error("Error occurred while de-activating Connected Cup Service Component", e);
} }
} }
} }

Loading…
Cancel
Save