private void subscribe ( final Session session, final MqttItemToTopic itemToTopic ) throws InvalidSessionException, InvalidItemException, MqttSecurityException, MqttException { this.executor.submit ( new Callable<Void> () { @Override public Void call () throws Exception { logger.trace ( "subscribe () called with {}", itemToTopic ); if ( itemToTopic.isWritable () ) { logger.trace ( "subscribe () called on topic '{}'", makeWriteTopicName ( itemToTopic ) ); MqttExporter.this.client.subscribe ( makeWriteTopicName ( itemToTopic ) ); MqttExporter.this.itemsToWriteTopics.put ( itemToTopic.getItemId (), makeWriteTopicName ( itemToTopic ) ); } if ( itemToTopic.isReadable () ) { MqttExporter.this.hive.subscribeItem ( session, itemToTopic.getItemId () ); MqttExporter.this.itemsToReadTopics.put ( itemToTopic.getItemId (), makeReadTopicName ( itemToTopic ) ); } return null; } } ); }
/** * @see org.eclipse.paho.client.mqttv3.IMqttToken#waitForCompletion(long) */ @Override public void waitForCompletion(long timeout) throws MqttException, MqttSecurityException { synchronized (waitObject) { try { waitObject.wait(timeout); } catch (InterruptedException e) { // do nothing } if (!isComplete) { throw new MqttException(MqttException.REASON_CODE_CLIENT_TIMEOUT); } if (pendingException != null) { throw pendingException; } } }
/** * Get the SSLSocketFactory using SSL key store and password * <p> * A convenience method, which will help user to create a SSLSocketFactory * object * </p> * * @param keyStore * the SSL key store which is generated by some SSL key tool, * such as keytool in Java JDK * @param password * the password of the key store which is set when the key store * is generated * @return SSLSocketFactory used to connect to the server with SSL * authentication * @throws MqttSecurityException * if there was any error when getting the SSLSocketFactory */ public SSLSocketFactory getSSLSocketFactory (InputStream keyStore, String password) throws MqttSecurityException { try{ SSLContext ctx = null; SSLSocketFactory sslSockFactory=null; KeyStore ts; ts = KeyStore.getInstance("BKS"); ts.load(keyStore, password.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509"); tmf.init(ts); TrustManager[] tm = tmf.getTrustManagers(); ctx = SSLContext.getInstance("TLSv1"); ctx.init(null, tm, null); sslSockFactory=ctx.getSocketFactory(); return sslSockFactory; } catch (KeyStoreException | CertificateException | IOException | NoSuchAlgorithmException | KeyManagementException e) { throw new MqttSecurityException(e); } }
public void doMain(String... args) throws MqttSecurityException, MqttException, InterruptedException { CmdLineParser cmdLineParser = new CmdLineParser(this); try { cmdLineParser.parseArgument(args); } catch (CmdLineException e) { System.err.println(e.getMessage()); cmdLineParser.printUsage(System.err); return; } connectToMqttBroker(); try { wait4ever(); } finally { close(); } }
@Test(timeout = TIMEOUT) public void generatesBrokerEventOnDigitalPinChange() throws InterruptedException, MqttSecurityException, MqttException, IOException { int pin = 1; this.client.setThrottleMillis(0); this.client.setAnalogs(); this.client.setDigitals(pin); startAsync(client); simulateArduinoToMqtt(alpProtocolMessage(DIGITAL_PIN_READ).forPin(pin) .withValue(1)); tearDown(); assertThat(this.amc.hasReceived(), is(listWithSameOrder(MqttMessageBuilder .mqttMessageWithBasicTopic(TOPIC).digitalPin(pin) .hasValue(1)))); }
@Test(timeout = TIMEOUT) public void generatesBrokerEventOnAnalogPinChange() throws InterruptedException, MqttSecurityException, MqttException, IOException { int pin = 1; int value = 45; this.client.setThrottleMillis(0); this.client.setAnalogs(pin); this.client.setDigitals(); startAsync(this.client); simulateArduinoToMqtt(alpProtocolMessage(ANALOG_PIN_READ).forPin(pin) .withValue(value)); tearDown(); assertThat(this.amc.hasReceived(), is(listWithSameOrder(MqttMessageBuilder .mqttMessageWithBasicTopic(TOPIC).analogPin(pin) .hasValue(value)))); }
@Test(timeout = TIMEOUT) public void clientConnectsWhenAfterBrokerRestartet() throws InterruptedException, MqttSecurityException, MqttException, IOException { doNotListenForAnything(client); startAsync(client); MILLISECONDS.sleep(250); broker.stopServer(); MILLISECONDS.sleep(250); assertThat(client.isConnected(), is(false)); broker = startBroker(); waitUntilIsConnected(client, 3, SECONDS); assertThat(client.isConnected(), is(true)); tearDown(); }
@Test(timeout = TIMEOUT) public void processesBrokerEventPowerOnDigitalPin() throws InterruptedException, MqttSecurityException, MqttException, IOException { int pin = 1; int value = 1; doNotListenForAnything(client); startAsync(client); amc.switchDigitalPin(pin, true); tearDown(); verify(link).getPortList(); verify(link).connect(PORT, SPEED); verify(link).sendPowerPinSwitch(pin, value); verify(link).isConnected(); verify(link).disconnect(); verifyNoMoreInteractions(link); }
@Test(timeout = TIMEOUT) public void processesBrokerEventPowerOnAnalogPin() throws InterruptedException, MqttSecurityException, MqttException, IOException { int pin = 1; int value = 123; doNotListenForAnything(client); startAsync(client); amc.switchAnalogPin(pin, value); tearDown(); verify(link).getPortList(); verify(link).connect(PORT, SPEED); verify(link).sendPowerPinIntensity(pin, value); verify(link).isConnected(); verify(link).disconnect(); verifyNoMoreInteractions(link); }
private static void initClient() throws MqttException, MqttSecurityException { if (client == null || !client.isConnected()) { UUID uuid = UUID.randomUUID(); String randomUUIDString = uuid.toString(); client = new MqttClient("tcp://localhost:1883", "HomeAutomation/" + randomUUIDString); MqttConnectOptions connOpt = new MqttConnectOptions(); connOpt.setAutomaticReconnect(true); connOpt.setCleanSession(true); connOpt.setKeepAliveInterval(60); connOpt.setConnectionTimeout(30); connOpt.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1); // connOpt.setUserName(M2MIO_USERNAME); // connOpt.setPassword(M2MIO_PASSWORD_MD5.toCharArray()); client.connect(connOpt); } }
private void connect() throws MqttException, MqttSecurityException { UUID uuid = UUID.randomUUID(); String randomUUIDString = uuid.toString(); client = new MqttClient("tcp://localhost:1883", "HomeAutomation/" + randomUUIDString, memoryPersistence); client.setCallback(this); MqttConnectOptions connOpt = new MqttConnectOptions(); connOpt.setAutomaticReconnect(true); // connOpt.setCleanSession(true); connOpt.setKeepAliveInterval(60); connOpt.setConnectionTimeout(60); connOpt.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1); // connOpt.setUserName(M2MIO_USERNAME); // connOpt.setPassword(M2MIO_PASSWORD_MD5.toCharArray()); client.connect(connOpt); client.subscribe("/sensordata"); client.subscribe("/sensorState"); client.subscribe("/distanceSensor"); client.subscribe("/switch"); LogManager.getLogger(this.getClass()).info("Started MQTT client"); }
private void connectClient() throws MqttSecurityException, MqttException { writeServiceTraceEntry(clsName, "connectClient", "Entry"); try { writeServiceTraceData(clsName, "connectClient", "Attempting to connect ..."); client.connect(); writeActivityLog("12063", new String[] { connectionUrl }, activityLogTag); // QoS defaults to 0. // int qos = getMQTTFactory().getQos(getProperties()); int qos = 0; client.subscribe(getProperties().getProperty("topicName"), qos); failedToConnect = false; writeServiceTraceData(clsName, "connectClient", "Connected OK."); writeActivityLog("12066", new String[] {getProperties().getProperty("topicName"), "" + qos}, activityLogTag); } catch (MbException e) { try { getConnectorFactory().getContainerServices().writeSystemLogError("2111", new String[]{e.getLocalizedMessage()}); } catch (MbException e1) { } } finally { writeServiceTraceExit(clsName, "connectClient", "Exit"); } }
/** * @see org.eclipse.paho.client.mqttv3.IMqttToken#waitForCompletion() */ @Override public void waitForCompletion() throws MqttException, MqttSecurityException { synchronized (waitObject) { try { waitObject.wait(); } catch (InterruptedException e) { // do nothing } } if (pendingException != null) { throw pendingException; } }
private void doConnect(MqttConnectOptions options) { if (options == null) options = buildOptions(); try { IMqttToken token = socketClient.connect(options); token.waitForCompletion(); System.out.println("Connected ;)"); emit("socket::connected"); for(int i = pubs.size();i>0;i--){ PublishHolder pub= pubs.peekFirst(); doPublish(pub); } } catch (MqttException e) { System.out.println("Failed to connect because;"); e.printStackTrace(); if (e.getReasonCode() == MqttSecurityException.REASON_CODE_NOT_AUTHORIZED || e.getReasonCode() == MqttSecurityException.REASON_CODE_SERVER_CONNECT_ERROR) { reconnect(false); } else if(e.getReasonCode() == MqttException.REASON_CODE_CLIENT_CLOSED || e.getReasonCode() == MqttException.REASON_CODE_CLIENT_CONNECTED) { }else { retryReconnect(options); } } }
public void connectToMqttBroker() throws MqttSecurityException, MqttException, InterruptedException { this.link = connect(createLink()); SECONDS.sleep(this.sleepSecs); // ensure brokerTopic is normalized setBrokerTopic(this.brokerTopic); Config config = Config.withTopic(this.brokerTopic); this.mqttClient = new MqttClient(link, this.control ? config.withControlChannelEnabled() : config) .listenToMqttAndArduino(); }
/** * Returns an SSL socket factory for the given configuration. If no * SSLProtocol is already set, uses DEFAULT_PROTOCOL. Throws * IllegalArgumentException if the socket factory could not be created due * to underlying configuration problems. * * @param configID The configuration identifier for selecting a configuration. * @return An SSLSocketFactory * @throws MqttDirectException * @see org.eclipse.paho.client.mqttv3.internal.security.SSLSocketFactoryFactory#DEFAULT_PROTOCOL */ public SSLSocketFactory createSocketFactory(String configID) throws MqttSecurityException { final String METHOD_NAME = "createSocketFactory"; SSLContext ctx = getSSLContext(configID); if (logger != null) { // 12020 "SSL initialization: configID = {0}, application-enabled cipher suites = {1}" logger.fine(CLASS_NAME, METHOD_NAME, "12020", new Object[]{configID != null ? configID : "null (broker defaults)", getEnabledCipherSuites(configID) != null ? getProperty(configID, CIPHERSUITES, null) : "null (using platform-enabled cipher suites)"}); } return ctx.getSocketFactory(); }
public static MqttException createMqttException(int reasonCode) { if ((reasonCode == MqttException.REASON_CODE_FAILED_AUTHENTICATION) || (reasonCode == MqttException.REASON_CODE_NOT_AUTHORIZED)) { return new MqttSecurityException(reasonCode); } return new MqttException(reasonCode); }
/** * Returns an SSL socket factory for the given configuration. If no * SSLProtocol is already set, uses DEFAULT_PROTOCOL. Throws * IllegalArgumentException if the socket factory could not be created due * to underlying configuration problems. * * @see org.eclipse.paho.client.mqttv3.internal.security.SSLSocketFactoryFactory#DEFAULT_PROTOCOL * @param configID * The configuration identifier for selecting a configuration. * @return An SSLSocketFactory * @throws MqttDirectException */ public SSLSocketFactory createSocketFactory(String configID) throws MqttSecurityException { final String METHOD_NAME = "createSocketFactory"; SSLContext ctx = getSSLContext(configID); if (logger != null) { // 12020 "SSL initialization: configID = {0}, application-enabled cipher suites = {1}" logger.fine(CLASS_NAME, METHOD_NAME, "12020", new Object[]{configID!=null ? configID : "null (broker defaults)", getEnabledCipherSuites(configID)!=null ? getProperty(configID, CIPHERSUITES, null) : "null (using platform-enabled cipher suites)"}); } return ctx.getSocketFactory(); }
private MqttClient(Link link, Config config) throws MqttSecurityException, MqttException { super(link, config); this.client = newClient(brokerHost, brokerPort, clientId); this.client.setCallback(createCallback()); }
public MqttClient listenToMqttAndArduino() throws MqttSecurityException, MqttException { return listenToMqtt().listenToArduino(); }
private MqttClient listenToMqtt() throws MqttSecurityException, MqttException { connect(); subscribe(); return this; }
private org.eclipse.paho.client.mqttv3.MqttClient newClient( String host, int port, String clientId) throws MqttException, MqttSecurityException { return new org.eclipse.paho.client.mqttv3.MqttClient("tcp://" + host + ":" + port, clientId); }
private void connect() throws MqttSecurityException, MqttException { this.client.connect(mqttConnectOptions()); logger.info("Connected to mqtt broker"); publishClientStatus(TRUE); }
public static void main(String[] args) throws MqttSecurityException, MqttException, InterruptedException { new MqttMain().doMain(args); }
@Before public void setup() throws IOException, InterruptedException, MqttSecurityException, MqttException { this.broker = startBroker(); this.amc = new AnotherMqttClient(TOPIC).connect(); }
@Before public void setup() throws IOException, InterruptedException, MqttSecurityException, MqttException { broker = startBroker(); }
@Before public void setup() throws IOException, InterruptedException, MqttSecurityException, MqttException { broker = startBroker(); amc = new AnotherMqttClient(TOPIC).connect(); }
public static MqttMain startAsync(MqttMain mqttMain) throws InterruptedException, MqttSecurityException, MqttException { mqttMain.connectToMqttBroker(); return waitUntilIsConnected(mqttMain, 5, SECONDS); }
public AnotherMqttClient connect() throws MqttSecurityException, MqttException { mqttClient.connect(); mqttClient.subscribe("#"); return this; }
private void setupConnectWithSecurityException() throws Exception { doThrow(new MqttSecurityException(1)).when(mockClient).connect((MqttConnectOptions) anyObject()); }
public static MqttException createMqttException(Throwable cause) { if (cause.getClass().getName().equals("java.security.GeneralSecurityException")) { return new MqttSecurityException(cause); } return new MqttException(cause); }
/** * Connect to the MQTT server specified by a particular client * * @param clientHandle * identifies the MqttConnection to use * @param connectOptions * the MQTT connection options to be used * @param invocationContext * arbitrary data to be passed back to the application * @param activityToken * arbitrary identifier to be passed back to the Activity * @throws MqttSecurityException thrown if there is a security exception * @throws MqttException thrown for all other MqttExceptions */ public void connect(String clientHandle, MqttConnectOptions connectOptions, String invocationContext, String activityToken) throws MqttSecurityException, MqttException { MqttConnection client = getConnection(clientHandle); client.connect(connectOptions, null, activityToken); }
/** * Connect to the MQTT server specified by a particular client * * @param clientHandle * identifies the MqttConnection to use * @param connectOptions * the MQTT connection options to be used * @param invocationContext * arbitrary data to be passed back to the application * @param activityToken * arbitrary identifier to be passed back to the Activity * @throws org.eclipse.paho.client.mqttv3.MqttSecurityException * @throws org.eclipse.paho.client.mqttv3.MqttException */ public void connect(String clientHandle, MqttConnectOptions connectOptions, String invocationContext, String activityToken) throws MqttSecurityException, MqttException { MqttConnection client = getConnection(clientHandle); client.connect(connectOptions, invocationContext, activityToken); }
/** * Connect to the MQTT server specified by a particular client * * @param clientHandle * identifies the MqttConnection to use * @param connectOptions * the MQTT connection options to be used * @param invocationContext * arbitrary data to be passed back to the application * @param activityToken * arbitrary identifier to be passed back to the Activity * @throws MqttSecurityException * @throws MqttException */ public void connect(String clientHandle, MqttConnectOptions connectOptions, String invocationContext, String activityToken) throws MqttSecurityException, MqttException { MqttConnection client = getConnection(clientHandle); client.connect(connectOptions, invocationContext, activityToken); }