private void doConnect() { L.info( "Connecting to MQTT broker " + mqttc.getServerURI() + " with CLIENTID=" + mqttc.getClientId() + " and TOPIC PREFIX=" + topicPrefix); MqttConnectOptions copts = new MqttConnectOptions(); copts.setWill(topicPrefix + "connected", "0".getBytes(), 1, true); copts.setCleanSession(true); copts.setUserName("emonpi"); copts.setPassword("emonpimqtt2016".toCharArray()); try { mqttc.connect(copts); sendConnectionState(); L.info("Successfully connected to broker, subscribing to " + topicPrefix + "(set|get)/#"); try { mqttc.subscribe(topicPrefix + "set/#", 1); mqttc.subscribe(topicPrefix + "get/#", 1); shouldBeConnected = true; } catch (MqttException mqe) { L.log(Level.WARNING, "Error subscribing to topic hierarchy, check your configuration", mqe); throw mqe; } } catch (MqttException mqe) { L.log( Level.WARNING, "Error while connecting to MQTT broker, will retry: " + mqe.getMessage(), mqe); queueConnect(); // Attempt reconnect } }
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); }