public void startListener() throws MqttException {
   if (this.mqttBrokerConnectionConfiguration.getBrokerUsername() != null
       && this.mqttBrokerConnectionConfiguration.getDcrUrl() != null) {
     String username = this.mqttBrokerConnectionConfiguration.getBrokerUsername();
     String dcrUrlString = this.mqttBrokerConnectionConfiguration.getDcrUrl();
     String scopes = this.mqttBrokerConnectionConfiguration.getBrokerScopes();
     // getJWT Client Parameters.
     if (dcrUrlString != null && !dcrUrlString.isEmpty()) {
       PrivilegedCarbonContext.startTenantFlow();
       PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true);
       PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(username);
       try {
         URL dcrUrl = new URL(dcrUrlString);
         HttpClient httpClient = MQTTUtil.getHttpClient(dcrUrl.getProtocol());
         HttpPost postMethod = new HttpPost(dcrUrlString);
         RegistrationProfile registrationProfile = new RegistrationProfile();
         registrationProfile.setCallbackUrl(MQTTEventAdapterConstants.EMPTY_STRING);
         registrationProfile.setGrantType(MQTTEventAdapterConstants.GRANT_TYPE);
         registrationProfile.setOwner(username);
         registrationProfile.setTokenScope(MQTTEventAdapterConstants.TOKEN_SCOPE);
         registrationProfile.setApplicationType(MQTTEventAdapterConstants.APPLICATION_TYPE);
         registrationProfile.setClientName(username + "_" + tenantId);
         String jsonString = registrationProfile.toJSON();
         StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
         postMethod.setEntity(requestEntity);
         HttpResponse httpResponse = httpClient.execute(postMethod);
         if (httpResponse != null) {
           String response = MQTTUtil.getResponseString(httpResponse);
           try {
             if (response != null) {
               JSONParser jsonParser = new JSONParser();
               JSONObject jsonPayload = (JSONObject) jsonParser.parse(response);
               String clientId = (String) jsonPayload.get(MQTTEventAdapterConstants.CLIENT_ID);
               String clientSecret =
                   (String) jsonPayload.get(MQTTEventAdapterConstants.CLIENT_SECRET);
               JWTClientManagerService jwtClientManagerService =
                   MQTTUtil.getJWTClientManagerService();
               AccessTokenInfo accessTokenInfo =
                   jwtClientManagerService
                       .getJWTClient()
                       .getAccessToken(clientId, clientSecret, username, scopes);
               connectionOptions.setUserName(accessTokenInfo.getAccessToken());
             }
           } catch (ParseException e) {
             String msg = "error occurred while parsing client credential payload";
             log.error(msg, e);
           } catch (JWTClientException e) {
             String msg = "error occurred while parsing the response from JWT Client";
             log.error(msg, e);
           }
         }
       } catch (MalformedURLException e) {
         log.error("Invalid dcrUrl : " + dcrUrlString);
       } catch (KeyManagementException
           | NoSuchAlgorithmException
           | KeyStoreException
           | IOException e) {
         log.error("Failed to create an https connection.", e);
       } finally {
         PrivilegedCarbonContext.endTenantFlow();
       }
     }
   }
   mqttClient.connect(connectionOptions);
   mqttClient.subscribe(topic);
 }
  private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType)
      throws DeviceManagementException, APIManagerException, JWTClientException, UserStoreException,
          VirtualFirealarmDeviceMgtPluginException {
    // create new device id
    String deviceId = shortUUID();
    boolean status = register(deviceId, deviceName);
    if (!status) {
      String msg =
          "Error occurred while registering the device with "
              + "id: "
              + deviceId
              + " owner:"
              + owner;
      throw new DeviceManagementException(msg);
    }
    if (apiApplicationKey == null) {
      String applicationUsername =
          PrivilegedCarbonContext.getThreadLocalCarbonContext()
              .getUserRealm()
              .getRealmConfiguration()
              .getAdminUserName();
      APIManagementProviderService apiManagementProviderService =
          APIUtil.getAPIManagementProviderService();
      String[] tags = {VirtualFireAlarmConstants.DEVICE_TYPE};
      apiApplicationKey =
          apiManagementProviderService.generateAndRetrieveApplicationKeys(
              VirtualFireAlarmConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
    }
    JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient();
    String device =
        "{ \"scope\":\"mqtt-publisher mqtt-subscriber\", \"deviceIdentifiers\":[{\"id\":\""
            + deviceId
            + "\", "
            + "\"type\":\""
            + VirtualFireAlarmConstants.DEVICE_TYPE
            + "\"}]}";
    Map<String, String> params = new HashMap<String, String>();
    params.put("device", Base64.encodeBase64String(device.getBytes()));
    AccessTokenInfo accessTokenInfo =
        jwtClient.getAccessToken(
            apiApplicationKey.getConsumerKey(),
            apiApplicationKey.getConsumerSecret(),
            owner,
            null,
            params);
    String accessToken = accessTokenInfo.getAccessToken();
    String refreshToken = accessTokenInfo.getRefreshToken();
    XmppAccount newXmppAccount = new XmppAccount();
    newXmppAccount.setAccountName(deviceId);
    newXmppAccount.setUsername(deviceId);
    newXmppAccount.setPassword(accessToken);
    newXmppAccount.setEmail(deviceId + "@" + APIUtil.getTenantDomainOftheUser());

    status = XmppServerClient.createAccount(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";
      throw new DeviceManagementException(msg);
    }
    ZipUtil ziputil = new ZipUtil();
    return ziputil.createZipFile(
        owner,
        sketchType,
        deviceId,
        deviceName,
        apiApplicationKey.toString(),
        accessToken,
        refreshToken);
  }