From 08c518c0c26281b1ccd02d4b5c29e415fbfe1b05 Mon Sep 17 00:00:00 2001 From: ayyoob Date: Mon, 12 Oct 2015 11:37:24 +0530 Subject: [PATCH] added api managed on virtual fire alarm and few changes on internal api --- modules/distribution/pom.xml | 83 ++- modules/distribution/src/assembly/bin.xml | 13 + .../src/repository/conf/axis2/axis2.xml | 510 ++++++------------ modules/p2-profile-gen/pom.xml | 30 ++ ...llerService.java => FireAlarmService.java} | 340 +++++++++++- .../src/main/webapp/WEB-INF/cxf-servlet.xml | 19 +- .../src/main/webapp/WEB-INF/web.xml | 50 ++ .../impl/VirtualFireAlarmManagerService.java | 359 ------------ ...vice.java => VirtualFireAlarmService.java} | 343 +++++++++++- .../src/main/webapp/WEB-INF/cxf-servlet.xml | 30 +- .../src/main/webapp/WEB-INF/web.xml | 50 ++ 11 files changed, 1050 insertions(+), 777 deletions(-) rename modules/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/{FireAlarmControllerService.java => FireAlarmService.java} (68%) delete mode 100644 modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/VirtualFireAlarmManagerService.java rename modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/{VirtualFireAlarmControllerService.java => VirtualFireAlarmService.java} (68%) diff --git a/modules/distribution/pom.xml b/modules/distribution/pom.xml index 08dc45ba..090f238b 100644 --- a/modules/distribution/pom.xml +++ b/modules/distribution/pom.xml @@ -442,31 +442,31 @@ (jdbc/WSO2CarbonDB) jdbc/WSO2AM_DB - - - - - - - - - - - - - - - - - - - - - - - - - + + /Server/OAuth/SupportedGrantTypes/SupportedGrantType + (org.wso2.carbon.identity.oauth2.token.handlers.grant.AuthorizationCodeGrantHandler) + org.wso2.carbon.apimgt.keymgt.handlers.ExtendedAuthorizationCodeGrantHandler + + + /Server/OAuth/SupportedGrantTypes/SupportedGrantType + (org.wso2.carbon.identity.oauth2.token.handlers.grant.PasswordGrantHandler) + org.wso2.carbon.apimgt.keymgt.handlers.ExtendedPasswordGrantHandler + + + /Server/OAuth/SupportedGrantTypes/SupportedGrantType + (org.wso2.carbon.identity.oauth2.token.handlers.grant.ClientCredentialsGrantHandler) + org.wso2.carbon.apimgt.keymgt.handlers.ExtendedClientCredentialsGrantHandler + + + /Server/OAuth/SupportedGrantTypes/SupportedGrantType + (org.wso2.carbon.identity.oauth2.token.handlers.grant.saml.SAML2BearerGrantHandler) + org.wso2.carbon.apimgt.keymgt.handlers.ExtendedSAML2BearerGrantHandler + + + /Server/OAuth/OAuthCallbackHandlers + (org.wso2.carbon.identity.oauth.callback.DefaultCallbackHandler) + org.wso2.carbon.apimgt.keymgt.util.APIManagerOAuthCallbackHandler + @@ -489,6 +489,39 @@ + + + replace-for-api-publisher + prepare-package + + replace + + + ${basedir}/../p2-profile-gen/target/wso2carbon-core-${carbon.platform.version}/repository/deployment/server/jaggeryapps/api-publisher/site/conf/site.json + + + (/publisher) + /api-publisher + + + + + + replace-for-api-store + prepare-package + + replace + + + ${basedir}/../p2-profile-gen/target/wso2carbon-core-${carbon.platform.version}/repository/deployment/server/jaggeryapps/api-store/site/conf/site.json + + + (/store) + /api-store + + + + diff --git a/modules/distribution/src/assembly/bin.xml b/modules/distribution/src/assembly/bin.xml index 006d8bf1..d263f48b 100644 --- a/modules/distribution/src/assembly/bin.xml +++ b/modules/distribution/src/assembly/bin.xml @@ -102,6 +102,15 @@ 755 + + + ../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/rxts + ${pom.artifactId}-${pom.version}/repository/resources/rxts/ + + *.rxt + + + @@ -381,6 +390,8 @@ **/org.wso2.ciphertool-1.0.0-wso2v3.jar + + @@ -391,6 +402,8 @@ + + diff --git a/modules/distribution/src/repository/conf/axis2/axis2.xml b/modules/distribution/src/repository/conf/axis2/axis2.xml index 4ac9c84f..7c3ce039 100644 --- a/modules/distribution/src/repository/conf/axis2/axis2.xml +++ b/modules/distribution/src/repository/conf/axis2/axis2.xml @@ -58,8 +58,8 @@ axis2modules - WSO2 IOT 1.0.0-SNAPSHOT - WSO2 IOT 1.0.0-SNAPSHOT + WSO2 IoTServer 1.0.0 + WSO2 IoTServer 1.0.0 @@ -153,7 +153,7 @@ + class="org.apache.synapse.commons.formatters.XFormURLEncodedFormatter"/> - - - - - - - + class="org.apache.synapse.commons.json.JsonStreamFormatter"/> - + class="org.wso2.carbon.relay.ExpandingMessageFormatter"/--> + + + + + + class="org.apache.synapse.format.hessian.HessianMessageFormatter"/--> + + @@ -229,158 +207,69 @@ - - - - - - - - + class="org.apache.synapse.commons.json.JsonStreamBuilder"/> - + class="org.wso2.carbon.relay.BinaryRelayBuilder"/--> + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + true + + + org.wso2.carbon.mediation.transport.handlers.PassThroughNHttpGetProcessor + + - - - - - - - - + true + TLSv1,TLSv1.1,TLSv1.2 + + + org.wso2.carbon.mediation.transport.handlers.PassThroughNHttpGetProcessor + + + repository/resources/security/wso2carbon.jks + JKS + wso2carbon + wso2carbon + + + + + repository/resources/security/client-truststore.jks + JKS + wso2carbon + + + + - - - - - - - - - - - - @@ -389,32 +278,27 @@ check com.sun.mail.pop3 and com.sun.mail.imap package documentation for more details--> - - - - - @@ -442,53 +326,75 @@ + + + - - - 9763 - - - - - - - - 9443 + + + + + + + - - - + - - - - - - + + + - + + true @@ -504,68 +410,18 @@ JKS wso2carbon - - - - + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + @@ -585,20 +441,16 @@ --> - - - - - - - - - - - - - - + + + + + + + + + @@ -607,13 +459,6 @@ - - - - @@ -646,7 +491,7 @@ is deemed to have left the cluster, it will be detected by the Group Membership Service (GMS) using a TCP ping mechanism. --> - multicast + wka @@ -690,7 +535,7 @@ The TCP port used by this member. This is the port through which other nodes will contact this member --> - 4000 + 4100 + + + + - @@ -768,17 +619,14 @@ - - + @@ -787,21 +635,19 @@ class="org.wso2.carbon.core.transports.smtp.SMTPFaultHandler"> - - - - - + + + + + @@ -841,7 +687,6 @@ - @@ -850,7 +695,7 @@ - @@ -879,17 +723,13 @@ class="org.apache.axis2.dispatchers.SOAPActionBasedDispatcher"> - - - @@ -934,4 +774,4 @@ - + \ No newline at end of file diff --git a/modules/p2-profile-gen/pom.xml b/modules/p2-profile-gen/pom.xml index d79a7376..24f5849c 100644 --- a/modules/p2-profile-gen/pom.xml +++ b/modules/p2-profile-gen/pom.xml @@ -100,6 +100,10 @@ + + + + @@ -378,6 +382,15 @@ org.wso2.carbon.apimgt:org.wso2.carbon.apimgt.startup.publisher.feature:${carbon.api.mgt.version} + + org.wso2.carbon.apimgt:org.wso2.carbon.apimgt.authenticator.oidc.feature:${carbon.api.mgt.version} + + + org.wso2.carbon.apimgt:org.wso2.carbon.apimgt.hostobjects.oidc.feature:${carbon.api.mgt.version} + + + + @@ -690,6 +703,11 @@ true + + + + + org.wso2.carbon.device.mgt.iot.feature.group @@ -1024,6 +1042,18 @@ org.wso2.carbon.apimgt.startup.publisher.feature.group ${carbon.api.mgt.version} + + + + + + org.wso2.carbon.apimgt.authenticator.oidc.feature.group + ${carbon.api.mgt.version} + + + org.wso2.carbon.apimgt.hostobjects.oidc.feature.group + ${carbon.api.mgt.version} + org.wso2.carbon.mediation.initializer.feature.group ${carbon.mediation.version} diff --git a/modules/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/FireAlarmControllerService.java b/modules/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/FireAlarmService.java similarity index 68% rename from modules/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/FireAlarmControllerService.java rename to modules/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/FireAlarmService.java index eb12180c..a3da1b6b 100644 --- a/modules/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/FireAlarmControllerService.java +++ b/modules/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/FireAlarmService.java @@ -16,6 +16,7 @@ package org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpResponse; @@ -26,26 +27,38 @@ import org.apache.http.impl.nio.client.HttpAsyncClients; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.analytics.exception.DataPublisherConfigurationException; import org.wso2.carbon.device.mgt.analytics.service.DeviceAnalyticsService; +import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.iot.common.DeviceController; +import org.wso2.carbon.device.mgt.iot.common.DeviceManagement; import org.wso2.carbon.device.mgt.iot.common.DeviceValidator; +import org.wso2.carbon.device.mgt.iot.common.apimgt.AccessTokenInfo; +import org.wso2.carbon.device.mgt.iot.common.apimgt.TokenClient; +import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppAccount; import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppConfig; -import org.wso2.carbon.device.mgt.iot.common.datastore.impl.DataStreamDefinitions; +import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppServerClient; +import org.wso2.carbon.device.mgt.iot.common.exception.AccessTokenException; import org.wso2.carbon.device.mgt.iot.common.exception.DeviceControllerException; -import org.wso2.carbon.device.mgt.iot.common.exception.UnauthorizedException; +import org.wso2.carbon.device.mgt.iot.common.util.ZipArchive; +import org.wso2.carbon.device.mgt.iot.common.util.ZipUtil; import org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.constants.FireAlarmConstants; import org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl.util.DeviceJSON; import org.wso2.carbon.utils.CarbonUtils; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.HttpMethod; import javax.ws.rs.POST; +import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @@ -57,17 +70,26 @@ import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; -public class FireAlarmControllerService { +//@Path("/FireAlarmDeviceManager") +public class FireAlarmService { + + private static Log log = LogFactory.getLog(FireAlarmService.class); - private static Log log = LogFactory.getLog(FireAlarmControllerService.class); //TODO; replace this tenant domain private final String SUPER_TENANT = "carbon.super"; @Context //injected response proxy supporting multiple thread private HttpServletResponse response; + private static final String TEMPERATURE_STREAM_DEFINITION = "org.wso2.iot.devices.temperature"; private static final String URL_PREFIX = "http://"; @@ -79,11 +101,303 @@ public class FireAlarmControllerService { public static final String HTTP_PROTOCOL = "HTTP"; public static final String MQTT_PROTOCOL = "MQTT"; + private static ConcurrentHashMap deviceToIpMap = new ConcurrentHashMap(); + + + @Path("manager/device/register") + @PUT + public boolean register(@QueryParam("deviceId") String deviceId, + @QueryParam("name") String name, @QueryParam("owner") String owner) { + + DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); + + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(FireAlarmConstants.DEVICE_TYPE); + try { + if (deviceManagement.getDeviceManagementService().isEnrolled(deviceIdentifier)) { + response.setStatus(Response.Status.CONFLICT.getStatusCode()); + return false; + } + + Device device = new Device(); + device.setDeviceIdentifier(deviceId); + EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); + + enrolmentInfo.setDateOfEnrolment(new Date().getTime()); + enrolmentInfo.setDateOfLastUpdate(new Date().getTime()); + enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); + enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); + + device.setName(name); + device.setType(FireAlarmConstants.DEVICE_TYPE); + enrolmentInfo.setOwner(owner); + device.setEnrolmentInfo(enrolmentInfo); + boolean added = deviceManagement.getDeviceManagementService().enrollDevice(device); + + if (added) { + response.setStatus(Response.Status.OK.getStatusCode()); + } else { + response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); + } + + return added; + } catch (DeviceManagementException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return false; + } finally { + deviceManagement.endTenantFlow(); + } + } + + @Path("manager/device/remove/{device_id}") + @DELETE + public void removeDevice(@PathParam("device_id") String deviceId, + @Context HttpServletResponse response) { + + DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(FireAlarmConstants.DEVICE_TYPE); + try { + boolean removed = deviceManagement.getDeviceManagementService().disenrollDevice( + deviceIdentifier); + if (removed) { + response.setStatus(Response.Status.OK.getStatusCode()); + + } else { + response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); + + } + } catch (DeviceManagementException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + } finally { + deviceManagement.endTenantFlow(); + } + + } + + @Path("manager/device/update/{device_id}") + @POST + public boolean updateDevice(@PathParam("device_id") String deviceId, + @QueryParam("name") String name, + @Context HttpServletResponse response) { + + DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); + + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(FireAlarmConstants.DEVICE_TYPE); + try { + Device device = deviceManagement.getDeviceManagementService().getDevice( + deviceIdentifier); + device.setDeviceIdentifier(deviceId); + + // device.setDeviceTypeId(deviceTypeId); + device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime()); + + device.setName(name); + device.setType(FireAlarmConstants.DEVICE_TYPE); + + boolean updated = deviceManagement.getDeviceManagementService().modifyEnrollment( + device); + + if (updated) { + response.setStatus(Response.Status.OK.getStatusCode()); + + } else { + response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); + + } + return updated; + } catch (DeviceManagementException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return false; + } finally { + deviceManagement.endTenantFlow(); + } + + } + + @Path("manager/device/{device_id}") + @GET + @Consumes("application/json") + @Produces("application/json") + public Device getDevice(@PathParam("device_id") String deviceId) { + + DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(FireAlarmConstants.DEVICE_TYPE); + + try { + return deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier); + + } catch (DeviceManagementException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return null; + } finally { + deviceManagement.endTenantFlow(); + } + + } + + @Path("manager/devices/{username}") + @GET + @Consumes("application/json") + @Produces("application/json") + public Device[] getFirealarmDevices(@PathParam("username") String username) { + + DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); + + try { + List userDevices = + deviceManagement.getDeviceManagementService().getDevicesOfUser( + username); + ArrayList userDevicesforFirealarm = new ArrayList(); + for (Device device : userDevices) { + + if (device.getType().equals(FireAlarmConstants.DEVICE_TYPE) && + device.getEnrolmentInfo().getStatus().equals( + EnrolmentInfo.Status.ACTIVE)) { + userDevicesforFirealarm.add(device); + + } + } + + return userDevicesforFirealarm.toArray(new Device[]{}); + } catch (DeviceManagementException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return null; + } finally { + deviceManagement.endTenantFlow(); + } + + } + + @Path("manager/device/{sketch_type}/download") + @GET + @Produces("application/octet-stream") + public Response downloadSketch(@QueryParam("owner") String owner, + @PathParam("sketch_type") String sketchType) { + + ZipArchive zipFile = null; + try { + zipFile = createDownloadFile(owner, sketchType); + Response.ResponseBuilder rb = Response.ok(zipFile.getZipFile()); + rb.header("Content-Disposition", + "attachment; filename=\"" + zipFile.getFileName() + "\""); + return rb.build(); + } catch (IllegalArgumentException ex) { + return Response.status(400).entity(ex.getMessage()).build();//bad request + } catch (DeviceManagementException ex) { + return Response.status(500).entity(ex.getMessage()).build(); + } catch (AccessTokenException ex) { + return Response.status(500).entity(ex.getMessage()).build(); + } catch (DeviceControllerException ex) { + return Response.status(500).entity(ex.getMessage()).build(); + } + + } + + @Path("manager/device/{sketch_type}/generate_link") + @GET + public Response generateSketchLink(@QueryParam("owner") String owner, + @PathParam("sketch_type") String sketchType) { + + ZipArchive zipFile = null; + try { + zipFile = createDownloadFile(owner, sketchType); + Response.ResponseBuilder rb = Response.ok(zipFile.getDeviceId()); + return rb.build(); + } catch (IllegalArgumentException ex) { + return Response.status(400).entity(ex.getMessage()).build();//bad request + } catch (DeviceManagementException ex) { + return Response.status(500).entity(ex.getMessage()).build(); + } catch (AccessTokenException ex) { + return Response.status(500).entity(ex.getMessage()).build(); + } catch (DeviceControllerException ex) { + return Response.status(500).entity(ex.getMessage()).build(); + } + + } + + private ZipArchive createDownloadFile(String owner, String sketchType) + throws DeviceManagementException, AccessTokenException, DeviceControllerException { + if (owner == null) { + throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!"); + } + + //create new device id + String deviceId = shortUUID(); + + TokenClient accessTokenClient = new TokenClient(FireAlarmConstants.DEVICE_TYPE); + AccessTokenInfo accessTokenInfo = null; + + accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId); + + //create token + String accessToken = accessTokenInfo.getAccess_token(); + String refreshToken = accessTokenInfo.getRefresh_token(); + //adding registering data + + + + XmppAccount newXmppAccount = new XmppAccount(); + newXmppAccount.setAccountName(owner + "_" + deviceId); + newXmppAccount.setUsername(deviceId); + newXmppAccount.setPassword(accessToken); - private static ConcurrentHashMap deviceToIpMap = - new ConcurrentHashMap(); + String xmppEndPoint = XmppConfig.getInstance().getXmppControlQueue().getServerURL(); + + int indexOfChar = xmppEndPoint.lastIndexOf('/'); + + if (indexOfChar != -1) { + xmppEndPoint = xmppEndPoint.substring((indexOfChar + 1), xmppEndPoint.length()); + } + + newXmppAccount.setEmail(deviceId + "@wso2.com"); + + XmppServerClient xmppServerClient = new XmppServerClient(); + xmppServerClient.initControlQueue(); + boolean status; + if(XmppConfig.getInstance().isEnabled()) { + status = xmppServerClient.createXMPPAccount(newXmppAccount); + + if (!status) { + String msg = + "XMPP Account was not created for device - " + deviceId + " of owner - " + + owner + + ". XMPP might have been disabled in org.wso2.carbon.device.mgt.iot.common.config.server.configs"; + log.warn(msg); + throw new DeviceManagementException(msg); + } + } + status = register(deviceId, owner + "s_" + sketchType + "_" + deviceId.substring(0, + 3), + owner); + if (!status) { + String msg = "Error occurred while registering the device with " + "id: " + deviceId + + " owner:" + owner; + throw new DeviceManagementException(msg); + } + + + ZipUtil ziputil = new ZipUtil(); + ZipArchive zipFile = null; + + zipFile = ziputil.downloadSketch(owner,SUPER_TENANT, sketchType, deviceId, accessToken, refreshToken); + zipFile.setDeviceId(deviceId); + return zipFile; + } + + 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("/register/{owner}/{deviceId}/{ip}") + @Path("controller/register/{owner}/{deviceId}/{ip}") @POST public String registerDeviceIP(@PathParam("owner") String owner, @PathParam("deviceId") String deviceId, @@ -109,7 +423,7 @@ public class FireAlarmControllerService { /* Service to switch "ON" and "OFF" the FireAlarm bulb Called by an external client intended to control the FireAlarm bulb */ - @Path("/bulb/{state}") + @Path("controller/bulb/{state}") @POST public void switchBulb(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId, @@ -184,7 +498,7 @@ public class FireAlarmControllerService { } - @Path("/readsonar") + @Path("controller/readsonar") @GET public String requestSonarReading(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId, @@ -255,7 +569,7 @@ public class FireAlarmControllerService { } - @Path("/readtemperature") + @Path("controller/readtemperature") @GET public String requestTemperature(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId, @@ -375,7 +689,7 @@ public class FireAlarmControllerService { // return replyMsg; // } - @Path("/push_temperature") + @Path("/controller/push_temperature") @POST @Consumes(MediaType.APPLICATION_JSON) public void pushTemperatureData( @@ -389,12 +703,12 @@ public class FireAlarmControllerService { if (registeredIp == null) { log.warn("Unregistered IP: Temperature Data Received from an un-registered IP " + - deviceIp + " for device ID - " + deviceId); + deviceIp + " for device ID - " + deviceId); response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode()); return; } else if (!registeredIp.equals(deviceIp)) { log.warn("Conflicting IP: Received IP is " + deviceIp + ". Device with ID " + - deviceId + " is already registered under some other IP. Re-registration " + "required"); + deviceId + " is already registered under some other IP. Re-registration " + "required"); response.setStatus(Response.Status.CONFLICT.getStatusCode()); return; } diff --git a/modules/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml b/modules/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml index 69cc179b..8b358030 100644 --- a/modules/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml +++ b/modules/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -22,23 +22,10 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"> - - - - - - - - - - - - - + - + diff --git a/modules/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/webapp/WEB-INF/web.xml b/modules/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/webapp/WEB-INF/web.xml index ee946a86..2a9994d5 100755 --- a/modules/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/webapp/WEB-INF/web.xml +++ b/modules/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/webapp/WEB-INF/web.xml @@ -19,5 +19,55 @@ /* + + isAdminService + false + + + doAuthentication + false + + + + + managed-api-enabled + true + + + managed-api-owner + admin + + + managed-api-name + firealarm + + + managed-api-endpoint + http://localhost:9763/firealarm + + + managed-api-version + 1.0.0 + + + managed-api-context + /firealarm + + + managed-api-isSecured + true + + + + + + + + + + + + + diff --git a/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/VirtualFireAlarmManagerService.java b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/VirtualFireAlarmManagerService.java deleted file mode 100644 index c75937cc..00000000 --- a/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/VirtualFireAlarmManagerService.java +++ /dev/null @@ -1,359 +0,0 @@ -/* - * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * Licensed 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.iot.sample.virtual.firealarm.service.impl; - - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.EnrolmentInfo; -import org.wso2.carbon.device.mgt.iot.common.DeviceManagement; -import org.wso2.carbon.device.mgt.iot.common.apimgt.AccessTokenInfo; -import org.wso2.carbon.device.mgt.iot.common.apimgt.TokenClient; -import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppAccount; -import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppConfig; -import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppServerClient; -import org.wso2.carbon.device.mgt.iot.common.exception.AccessTokenException; -import org.wso2.carbon.device.mgt.iot.common.exception.DeviceControllerException; -import org.wso2.carbon.device.mgt.iot.common.util.ZipArchive; -import org.wso2.carbon.device.mgt.iot.common.util.ZipUtil; -import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.constants - .VirtualFireAlarmConstants; - -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.UUID; - -//@Path("/VirtualFireAlarmDeviceManager") -public class VirtualFireAlarmManagerService { - - private static Log log = LogFactory.getLog(VirtualFireAlarmManagerService.class); - - //TODO; replace this tenant domain - private final String SUPER_TENANT = "carbon.super"; - @Context //injected response proxy supporting multiple thread - private HttpServletResponse response; - - @Path("/device/register") - @PUT - public boolean register(@QueryParam("deviceId") String deviceId, - @QueryParam("name") String name, @QueryParam("owner") String owner) { - - DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); - - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(deviceId); - deviceIdentifier.setType(VirtualFireAlarmConstants.DEVICE_TYPE); - try { - if (deviceManagement.getDeviceManagementService().isEnrolled(deviceIdentifier)) { - response.setStatus(Response.Status.CONFLICT.getStatusCode()); - return false; - } - - Device device = new Device(); - device.setDeviceIdentifier(deviceId); - EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); - - enrolmentInfo.setDateOfEnrolment(new Date().getTime()); - enrolmentInfo.setDateOfLastUpdate(new Date().getTime()); - enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); - enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); - - device.setName(name); - device.setType(VirtualFireAlarmConstants.DEVICE_TYPE); - enrolmentInfo.setOwner(owner); - device.setEnrolmentInfo(enrolmentInfo); - boolean added = deviceManagement.getDeviceManagementService().enrollDevice(device); - - if (added) { - response.setStatus(Response.Status.OK.getStatusCode()); - } else { - response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); - } - - return added; - } catch (DeviceManagementException e) { - response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); - return false; - } finally { - deviceManagement.endTenantFlow(); - } - } - - @Path("/device/remove/{device_id}") - @DELETE - public void removeDevice(@PathParam("device_id") String deviceId, - @Context HttpServletResponse response) { - - DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(deviceId); - deviceIdentifier.setType(VirtualFireAlarmConstants.DEVICE_TYPE); - try { - boolean removed = deviceManagement.getDeviceManagementService().disenrollDevice( - deviceIdentifier); - if (removed) { - response.setStatus(Response.Status.OK.getStatusCode()); - - } else { - response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); - - } - } catch (DeviceManagementException e) { - response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); - } finally { - deviceManagement.endTenantFlow(); - } - - } - - @Path("/device/update/{device_id}") - @POST - public boolean updateDevice(@PathParam("device_id") String deviceId, - @QueryParam("name") String name, - @Context HttpServletResponse response) { - - DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); - - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(deviceId); - deviceIdentifier.setType(VirtualFireAlarmConstants.DEVICE_TYPE); - try { - Device device = deviceManagement.getDeviceManagementService().getDevice( - deviceIdentifier); - device.setDeviceIdentifier(deviceId); - - // device.setDeviceTypeId(deviceTypeId); - device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime()); - - device.setName(name); - device.setType(VirtualFireAlarmConstants.DEVICE_TYPE); - - boolean updated = deviceManagement.getDeviceManagementService().modifyEnrollment( - device); - - if (updated) { - response.setStatus(Response.Status.OK.getStatusCode()); - - } else { - response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); - - } - return updated; - } catch (DeviceManagementException e) { - response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); - return false; - } finally { - deviceManagement.endTenantFlow(); - } - - } - - @Path("/device/{device_id}") - @GET - @Consumes("application/json") - @Produces("application/json") - public Device getDevice(@PathParam("device_id") String deviceId) { - - DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(deviceId); - deviceIdentifier.setType(VirtualFireAlarmConstants.DEVICE_TYPE); - - try { - return deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier); - - } catch (DeviceManagementException e) { - response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); - return null; - } finally { - deviceManagement.endTenantFlow(); - } - - } - - @Path("/devices/{username}") - @GET - @Consumes("application/json") - @Produces("application/json") - public Device[] getFirealarmDevices(@PathParam("username") String username) { - - DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); - - try { - List userDevices = - deviceManagement.getDeviceManagementService().getDevicesOfUser( - username); - ArrayList userDevicesforFirealarm = new ArrayList(); - for (Device device : userDevices) { - - if (device.getType().equals(VirtualFireAlarmConstants.DEVICE_TYPE) && - device.getEnrolmentInfo().getStatus().equals( - EnrolmentInfo.Status.ACTIVE)) { - userDevicesforFirealarm.add(device); - - } - } - - return userDevicesforFirealarm.toArray(new Device[]{}); - } catch (DeviceManagementException e) { - response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); - return null; - } finally { - deviceManagement.endTenantFlow(); - } - - } - - @Path("/device/{sketch_type}/download") - @GET - @Produces("application/octet-stream") - public Response downloadSketch(@QueryParam("owner") String owner, - @PathParam("sketch_type") String sketchType) { - - ZipArchive zipFile = null; - try { - zipFile = createDownloadFile(owner, sketchType); - Response.ResponseBuilder rb = Response.ok(zipFile.getZipFile()); - rb.header("Content-Disposition", - "attachment; filename=\"" + zipFile.getFileName() + "\""); - return rb.build(); - } catch (IllegalArgumentException ex) { - return Response.status(400).entity(ex.getMessage()).build();//bad request - } catch (DeviceManagementException ex) { - return Response.status(500).entity(ex.getMessage()).build(); - } catch (AccessTokenException ex) { - return Response.status(500).entity(ex.getMessage()).build(); - } catch (DeviceControllerException ex) { - return Response.status(500).entity(ex.getMessage()).build(); - } - - } - - @Path("/device/{sketch_type}/generate_link") - @GET - public Response generateSketchLink(@QueryParam("owner") String owner, - @PathParam("sketch_type") String sketchType) { - - ZipArchive zipFile = null; - try { - zipFile = createDownloadFile(owner, sketchType); - Response.ResponseBuilder rb = Response.ok(zipFile.getDeviceId()); - return rb.build(); - } catch (IllegalArgumentException ex) { - return Response.status(400).entity(ex.getMessage()).build();//bad request - } catch (DeviceManagementException ex) { - return Response.status(500).entity(ex.getMessage()).build(); - } catch (AccessTokenException ex) { - return Response.status(500).entity(ex.getMessage()).build(); - } catch (DeviceControllerException ex) { - return Response.status(500).entity(ex.getMessage()).build(); - } - - } - - private ZipArchive createDownloadFile(String owner, String sketchType) - throws DeviceManagementException, AccessTokenException, DeviceControllerException { - if (owner == null) { - throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!"); - } - - //create new device id - String deviceId = shortUUID(); - - TokenClient accessTokenClient = new TokenClient("firealarm"); - AccessTokenInfo accessTokenInfo = null; - - accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId); - - //create token - String accessToken = accessTokenInfo.getAccess_token(); - String refreshToken = accessTokenInfo.getRefresh_token(); - //adding registering data - - XmppAccount newXmppAccount = new XmppAccount(); - newXmppAccount.setAccountName(owner + "_" + deviceId); - newXmppAccount.setUsername(deviceId); - newXmppAccount.setPassword(accessToken); - - String xmppEndPoint = XmppConfig.getInstance().getXmppControlQueue().getServerURL(); - - int indexOfChar = xmppEndPoint.lastIndexOf('/'); - - if (indexOfChar != -1) { - xmppEndPoint = xmppEndPoint.substring((indexOfChar + 1), xmppEndPoint.length()); - } - - newXmppAccount.setEmail(deviceId + "@wso2.com"); - - XmppServerClient xmppServerClient = new XmppServerClient(); - xmppServerClient.initControlQueue(); - boolean status; - if(XmppConfig.getInstance().isEnabled()) { - status = xmppServerClient.createXMPPAccount(newXmppAccount); - - if (!status) { - String msg = - "XMPP Account was not created for device - " + deviceId + " of owner - " + - owner + - ". XMPP might have been disabled in org.wso2.carbon.device.mgt.iot.common.config.server.configs"; - log.warn(msg); - throw new DeviceManagementException(msg); - } - } - status = register(deviceId, owner + "s_" + sketchType + "_" + deviceId.substring(0, - 3), - owner); - if (!status) { - String msg = "Error occurred while registering the device with " + "id: " + deviceId - + " owner:" + owner; - throw new DeviceManagementException(msg); - } - - - ZipUtil ziputil = new ZipUtil(); - ZipArchive zipFile = null; - - zipFile = ziputil.downloadSketch(owner,SUPER_TENANT, sketchType, deviceId, accessToken, refreshToken); - zipFile.setDeviceId(deviceId); - return zipFile; - } - - 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); - } - -} diff --git a/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/VirtualFireAlarmControllerService.java b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/VirtualFireAlarmService.java similarity index 68% rename from modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/VirtualFireAlarmControllerService.java rename to modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/VirtualFireAlarmService.java index aa5f6b76..d568427b 100644 --- a/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/VirtualFireAlarmControllerService.java +++ b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/VirtualFireAlarmService.java @@ -16,6 +16,7 @@ package org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpResponse; @@ -26,25 +27,39 @@ import org.apache.http.impl.nio.client.HttpAsyncClients; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.analytics.exception.DataPublisherConfigurationException; import org.wso2.carbon.device.mgt.analytics.service.DeviceAnalyticsService; +import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.iot.common.DeviceController; +import org.wso2.carbon.device.mgt.iot.common.DeviceManagement; import org.wso2.carbon.device.mgt.iot.common.DeviceValidator; +import org.wso2.carbon.device.mgt.iot.common.apimgt.AccessTokenInfo; +import org.wso2.carbon.device.mgt.iot.common.apimgt.TokenClient; +import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppAccount; import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppConfig; +import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppServerClient; +import org.wso2.carbon.device.mgt.iot.common.exception.AccessTokenException; import org.wso2.carbon.device.mgt.iot.common.exception.DeviceControllerException; -import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.util.DeviceJSON; +import org.wso2.carbon.device.mgt.iot.common.util.ZipArchive; +import org.wso2.carbon.device.mgt.iot.common.util.ZipUtil; import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.constants .VirtualFireAlarmConstants; +import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.util.DeviceJSON; import org.wso2.carbon.utils.CarbonUtils; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.HttpMethod; import javax.ws.rs.POST; +import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @@ -56,17 +71,26 @@ import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; -public class VirtualFireAlarmControllerService { +//@Path("/VirtualFireAlarmDeviceManager") +public class VirtualFireAlarmService { + + private static Log log = LogFactory.getLog(VirtualFireAlarmService.class); - private static Log log = LogFactory.getLog(VirtualFireAlarmControllerService.class); //TODO; replace this tenant domain private final String SUPER_TENANT = "carbon.super"; @Context //injected response proxy supporting multiple thread private HttpServletResponse response; + private static final String TEMPERATURE_STREAM_DEFINITION = "org.wso2.iot.devices.temperature"; private static final String URL_PREFIX = "http://"; @@ -82,7 +106,298 @@ public class VirtualFireAlarmControllerService { private static ConcurrentHashMap deviceToIpMap = new ConcurrentHashMap(); - @Path("/register/{owner}/{deviceId}/{ip}") + @Path("manager/device/register") + @PUT + public boolean register(@QueryParam("deviceId") String deviceId, + @QueryParam("name") String name, @QueryParam("owner") String owner) { + + DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); + + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(VirtualFireAlarmConstants.DEVICE_TYPE); + try { + if (deviceManagement.getDeviceManagementService().isEnrolled(deviceIdentifier)) { + response.setStatus(Response.Status.CONFLICT.getStatusCode()); + return false; + } + + Device device = new Device(); + device.setDeviceIdentifier(deviceId); + EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); + + enrolmentInfo.setDateOfEnrolment(new Date().getTime()); + enrolmentInfo.setDateOfLastUpdate(new Date().getTime()); + enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); + enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); + + device.setName(name); + device.setType(VirtualFireAlarmConstants.DEVICE_TYPE); + enrolmentInfo.setOwner(owner); + device.setEnrolmentInfo(enrolmentInfo); + boolean added = deviceManagement.getDeviceManagementService().enrollDevice(device); + + if (added) { + response.setStatus(Response.Status.OK.getStatusCode()); + } else { + response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); + } + + return added; + } catch (DeviceManagementException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return false; + } finally { + deviceManagement.endTenantFlow(); + } + } + + @Path("manager/device/remove/{device_id}") + @DELETE + public void removeDevice(@PathParam("device_id") String deviceId, + @Context HttpServletResponse response) { + + DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(VirtualFireAlarmConstants.DEVICE_TYPE); + try { + boolean removed = deviceManagement.getDeviceManagementService().disenrollDevice( + deviceIdentifier); + if (removed) { + response.setStatus(Response.Status.OK.getStatusCode()); + + } else { + response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); + + } + } catch (DeviceManagementException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + } finally { + deviceManagement.endTenantFlow(); + } + + } + + @Path("manager/device/update/{device_id}") + @POST + public boolean updateDevice(@PathParam("device_id") String deviceId, + @QueryParam("name") String name, + @Context HttpServletResponse response) { + + DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); + + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(VirtualFireAlarmConstants.DEVICE_TYPE); + try { + Device device = deviceManagement.getDeviceManagementService().getDevice( + deviceIdentifier); + device.setDeviceIdentifier(deviceId); + + // device.setDeviceTypeId(deviceTypeId); + device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime()); + + device.setName(name); + device.setType(VirtualFireAlarmConstants.DEVICE_TYPE); + + boolean updated = deviceManagement.getDeviceManagementService().modifyEnrollment( + device); + + if (updated) { + response.setStatus(Response.Status.OK.getStatusCode()); + + } else { + response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); + + } + return updated; + } catch (DeviceManagementException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return false; + } finally { + deviceManagement.endTenantFlow(); + } + + } + + @Path("manager/device/{device_id}") + @GET + @Consumes("application/json") + @Produces("application/json") + public Device getDevice(@PathParam("device_id") String deviceId) { + + DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(VirtualFireAlarmConstants.DEVICE_TYPE); + + try { + return deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier); + + } catch (DeviceManagementException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return null; + } finally { + deviceManagement.endTenantFlow(); + } + + } + + @Path("manager/devices/{username}") + @GET + @Consumes("application/json") + @Produces("application/json") + public Device[] getFirealarmDevices(@PathParam("username") String username) { + + DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); + + try { + List userDevices = + deviceManagement.getDeviceManagementService().getDevicesOfUser( + username); + ArrayList userDevicesforFirealarm = new ArrayList(); + for (Device device : userDevices) { + + if (device.getType().equals(VirtualFireAlarmConstants.DEVICE_TYPE) && + device.getEnrolmentInfo().getStatus().equals( + EnrolmentInfo.Status.ACTIVE)) { + userDevicesforFirealarm.add(device); + + } + } + + return userDevicesforFirealarm.toArray(new Device[]{}); + } catch (DeviceManagementException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return null; + } finally { + deviceManagement.endTenantFlow(); + } + + } + + @Path("manager/device/{sketch_type}/download") + @GET + @Produces("application/octet-stream") + public Response downloadSketch(@QueryParam("owner") String owner, + @PathParam("sketch_type") String sketchType) { + + ZipArchive zipFile = null; + try { + zipFile = createDownloadFile(owner, sketchType); + Response.ResponseBuilder rb = Response.ok(zipFile.getZipFile()); + rb.header("Content-Disposition", + "attachment; filename=\"" + zipFile.getFileName() + "\""); + return rb.build(); + } catch (IllegalArgumentException ex) { + return Response.status(400).entity(ex.getMessage()).build();//bad request + } catch (DeviceManagementException ex) { + return Response.status(500).entity(ex.getMessage()).build(); + } catch (AccessTokenException ex) { + return Response.status(500).entity(ex.getMessage()).build(); + } catch (DeviceControllerException ex) { + return Response.status(500).entity(ex.getMessage()).build(); + } + + } + + @Path("manager/device/{sketch_type}/generate_link") + @GET + public Response generateSketchLink(@QueryParam("owner") String owner, + @PathParam("sketch_type") String sketchType) { + + ZipArchive zipFile = null; + try { + zipFile = createDownloadFile(owner, sketchType); + Response.ResponseBuilder rb = Response.ok(zipFile.getDeviceId()); + return rb.build(); + } catch (IllegalArgumentException ex) { + return Response.status(400).entity(ex.getMessage()).build();//bad request + } catch (DeviceManagementException ex) { + return Response.status(500).entity(ex.getMessage()).build(); + } catch (AccessTokenException ex) { + return Response.status(500).entity(ex.getMessage()).build(); + } catch (DeviceControllerException ex) { + return Response.status(500).entity(ex.getMessage()).build(); + } + + } + + private ZipArchive createDownloadFile(String owner, String sketchType) + throws DeviceManagementException, AccessTokenException, DeviceControllerException { + if (owner == null) { + throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!"); + } + + //create new device id + String deviceId = shortUUID(); + + TokenClient accessTokenClient = new TokenClient("firealarm"); + AccessTokenInfo accessTokenInfo = null; + + accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId); + + //create token + String accessToken = accessTokenInfo.getAccess_token(); + String refreshToken = accessTokenInfo.getRefresh_token(); + //adding registering data + + XmppAccount newXmppAccount = new XmppAccount(); + newXmppAccount.setAccountName(owner + "_" + deviceId); + newXmppAccount.setUsername(deviceId); + newXmppAccount.setPassword(accessToken); + + String xmppEndPoint = XmppConfig.getInstance().getXmppControlQueue().getServerURL(); + + int indexOfChar = xmppEndPoint.lastIndexOf('/'); + + if (indexOfChar != -1) { + xmppEndPoint = xmppEndPoint.substring((indexOfChar + 1), xmppEndPoint.length()); + } + + newXmppAccount.setEmail(deviceId + "@wso2.com"); + + XmppServerClient xmppServerClient = new XmppServerClient(); + xmppServerClient.initControlQueue(); + boolean status; + if(XmppConfig.getInstance().isEnabled()) { + status = xmppServerClient.createXMPPAccount(newXmppAccount); + + if (!status) { + String msg = + "XMPP Account was not created for device - " + deviceId + " of owner - " + + owner + + ". XMPP might have been disabled in org.wso2.carbon.device.mgt.iot.common.config.server.configs"; + log.warn(msg); + throw new DeviceManagementException(msg); + } + } + status = register(deviceId, owner + "s_" + sketchType + "_" + deviceId.substring(0, + 3), + owner); + if (!status) { + String msg = "Error occurred while registering the device with " + "id: " + deviceId + + " owner:" + owner; + throw new DeviceManagementException(msg); + } + + + ZipUtil ziputil = new ZipUtil(); + ZipArchive zipFile = null; + + zipFile = ziputil.downloadSketch(owner,SUPER_TENANT, sketchType, deviceId, accessToken, refreshToken); + zipFile.setDeviceId(deviceId); + return zipFile; + } + + 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("controller/register/{owner}/{deviceId}/{ip}") @POST public String registerDeviceIP(@PathParam("owner") String owner, @PathParam("deviceId") String deviceId, @@ -108,7 +423,7 @@ public class VirtualFireAlarmControllerService { /* Service to switch "ON" and "OFF" the Virtual FireAlarm bulb Called by an external client intended to control the Virtual FireAlarm bulb */ - @Path("/bulb/{state}") + @Path("controller/bulb/{state}") @POST public void switchBulb(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId, @@ -119,7 +434,7 @@ public class VirtualFireAlarmControllerService { try { DeviceValidator deviceValidator = new DeviceValidator(); if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId, - VirtualFireAlarmConstants.DEVICE_TYPE))) { + VirtualFireAlarmConstants.DEVICE_TYPE))) { response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode()); return; } @@ -183,7 +498,7 @@ public class VirtualFireAlarmControllerService { } - @Path("/readsonar") + @Path("controller/readsonar") @GET public String requestSonarReading(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId, @@ -194,7 +509,7 @@ public class VirtualFireAlarmControllerService { DeviceValidator deviceValidator = new DeviceValidator(); try { if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId, - VirtualFireAlarmConstants + VirtualFireAlarmConstants .DEVICE_TYPE))) { response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode()); return "Unauthorized Access"; @@ -254,7 +569,7 @@ public class VirtualFireAlarmControllerService { } - @Path("/readtemperature") + @Path("controller/readtemperature") @GET public String requestTemperature(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId, @@ -265,7 +580,7 @@ public class VirtualFireAlarmControllerService { DeviceValidator deviceValidator = new DeviceValidator(); try { if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId, - VirtualFireAlarmConstants + VirtualFireAlarmConstants .DEVICE_TYPE))) { response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode()); return "Unauthorized Access"; @@ -374,7 +689,7 @@ public class VirtualFireAlarmControllerService { // return replyMsg; // } - @Path("/push_temperature") + @Path("controller/push_temperature") @POST @Consumes(MediaType.APPLICATION_JSON) public void pushTemperatureData( @@ -388,12 +703,12 @@ public class VirtualFireAlarmControllerService { if (registeredIp == null) { log.warn("Unregistered IP: Temperature Data Received from an un-registered IP " + - deviceIp + " for device ID - " + deviceId); + deviceIp + " for device ID - " + deviceId); response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode()); return; } else if (!registeredIp.equals(deviceIp)) { log.warn("Conflicting IP: Received IP is " + deviceIp + ". Device with ID " + - deviceId + " is already registered under some other IP. Re-registration " + "required"); + deviceId + " is already registered under some other IP. Re-registration " + "required"); response.setStatus(Response.Status.CONFLICT.getStatusCode()); return; } @@ -592,7 +907,7 @@ public class VirtualFireAlarmControllerService { try { result = deviceController.publishMqttControl(deviceOwner, - VirtualFireAlarmConstants.DEVICE_TYPE, + VirtualFireAlarmConstants.DEVICE_TYPE, deviceId, resource, state); } catch (DeviceControllerException e) { String errorMsg = "Error whilst trying to publish to MQTT Queue"; diff --git a/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml index dc3ddaab..83787aff 100644 --- a/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml +++ b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -23,22 +23,22 @@ http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"> - + + + + + + + + + + + + + - - - - - - - - - - - - + diff --git a/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/webapp/WEB-INF/web.xml b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/webapp/WEB-INF/web.xml index ee946a86..f9386313 100755 --- a/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/webapp/WEB-INF/web.xml +++ b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/webapp/WEB-INF/web.xml @@ -19,5 +19,55 @@ /* + + isAdminService + false + + + doAuthentication + false + + + + + managed-api-enabled + true + + + managed-api-owner + admin + + + managed-api-name + virtual_firealarm + + + managed-api-endpoint + http://localhost:9763/virtual_firealarm + + + managed-api-version + 1.0.0 + + + managed-api-context + /virtual_firealarm + + + managed-api-isSecured + true + + + + + + + + + + + + +